Let's say I have the following query:
query {
spreadsheet(id: 50) {
name,
user {
id, username
},
rows {id} # this is the foreign key that I need to call a function on
}
}
and my spreadsheet Model looks like:
class Spreadsheet:
objects = SpreadsheetManager()
user = models.ForeignKey(User)
name = models.CharField()
rows = model.ForeignKey(RowGenerator)
...
currently my query class looks like:
class Query(graphene.ObjectType):
spreadsheet = graphene.Field(SheetType,
id=graphene.Int(),
name=graphene.String()
)
resolve_sheet(self, info, **kwargs):
sheet_id = kwargs.get('id')
# name = kwargs.get('name')
if sheet_id is not None:
return Sheet.objects.select_related('user','rows').prefetch_related('projects').get(id=sheet_id)
return None
rows is a foreign key to an object, that upon calling a function generate_rows(), generates row data. Currently, my query returns the id of the foreign key, but what I want to do is to call a function on that object, (rows.generate_rows(), for example). How would it be possible to tell graphene to call that function on the field, once we retrieve it from the database?
would be happy to help contribute to this if this is currently not possible
This is definitely possible!
Have you defined DjangoObjectNodes for your models?
I would put a field on Rows called generated_rows that returns whatever type generate_rows produces. For the example i'll assume you want a list of strings
an example of your rows node might be
class RowsNow(DjangoObjectType):
class Meta:
model = Rows
generated_rows = graphene.List(graphene.String())
def resolve_generated_rows(instance, info, **kwargs):
return instance.generate_rows()
and then for your query you would do this
query {
spreadsheet(id: 50) {
name,
user {
id, username
},
rows {
id,
generatedRows
}
}
}
let me know if you have further questions!
This is phenomenal! I'm ecstatic. Thanks so much for the post.
@BossGrand Hey!
is there any way to filter rows?
for example, if we have person instead of rows, and it has first name and last name... is there anyway to do this? :
class PersonNode ( DjangoObjectType ):
class Meta:
model = Person
interfaces = ( graphene.relay.Node, )
filter_fields = {
'full_name': ['exact', 'icontains', 'istartswith'],
}
full_name = graphene.String()
def resolve_full_name ( instance, info, **kwargs ):
return " ".join([instance.first_name, instance.last_name])
@Mhs-220 did you ever figure out how to do this? I'm in the same boat.
Most helpful comment
@Mhs-220 did you ever figure out how to do this? I'm in the same boat.