How do we access calculated fields? In a serializer I would do something like
class ArtworkSerializer(serializers.ModelSerializer):
url = serializers.URLField(source='get_absolute_url')
class Meta:
model = Artwork
fields = ('id', 'title', 'url')
I assume I need to specify this somehow in class ArtworkNode(DjangoNode): but I've been unable to discover how.
Figured it out.
class ArtworkNode(DjangoNode):
url = graphene.String()
class Meta:
model = Artwork
filter_fields = ['id', 'title']
def resolve_url(self, args, info):
return self.instance.url
Is it possible to retrieve via pk?
Great! However I'm going to add the source option to fields! It makes it much more pleasant to develop!
So you can do something like
class ArtworkNode(DjangoNode):
url = graphene.String(source='get_absolute_url')
class Meta:
model = Artwork
filter_fields = ['id', 'title']
@sgtsquiggs You can retrieve an Artwork Node doing:
{
node(id:"SOME_STRING") {
id
}
}
In this case SOME_STRING will be the value of ArtworkNode.global_id(1).
Is it possible to get a single item via a field other than id? for instance I have a slug field on Artwork and in my django endpoint I use Artwork.get_by_slug(slug).
source= would be perfect, I use it extensively in my serializers
Sure. You can do it using arguments.
class Query(graphene.ObjectType):
artwork = graphene.Field(ArtworkNode, slug=graphene.String())
def resolve_artwork(self, args, info):
return Artwork.get_by_slug(args.get('slug', None))
Then you can query it with the following query:
{
artwork(slug:"my_slug") {
id
title
}
}
Hope it helps!
How do I resolve a django object along with an extra, calculated field like below during a query?
class ProjectType(DjangoObjectType):
class Meta:
model = Project
extra_field = graphene.String()
class Query(ObjectType):
project = graphene.Field(ProjectType,
name=graphene.String())
def resolve_project(self, info, name):
if id is not None:
return Project.objects.get(pk=id) # how do I populate `extra_field` here?
return None
Most helpful comment
Sure. You can do it using arguments.
Then you can query it with the following query:
Hope it helps!