Search code examples
djangodjango-modelsgraphene-python

How to get a list of all tags from Tagulous in Django Graphene


This is my model:

class FeedSource(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    feed = models.ForeignKey(Feed, on_delete=models.CASCADE) #FIXME: Deletion 
    title = models.CharField(max_length=200)
    show_on_frontpage = models.BooleanField(default=True)
    tags = TagField()

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["title"]
        unique_together = (("user", "feed"))

And this is my attempt to get all tags in schema.py:

class TagType(DjangoObjectType):

    class Meta:
        model = tagulous.models.TagModel
#        model = FeedSource
        interfaces = (graphene.relay.Node,)

class Query(graphene.ObjectType):
    all_tags = graphene.List(TagType, username=graphene.String(required=True))

    def resolve_all_tags(self, info, **kwargs):
        tags = FeedSource.tags.tag_model.objects.all()
        return tags

In graphiql I get the error: Expected value of type \"TagType\" but got: Tagulous_FeedSource_tags."

How can I set the model so that GraphQL will work and I can retrieve a list of all my tags?


Solution

  • By default Tagulous auto-generates a unique tag model each time you use a TagField - here it has generated the model Tagulous_FeedSource_tags (also accessible as FeedSource.tags.tag_model), so you're referencing the abstract model instead of the specific tag model for your field.

    Based on my understanding of graphene I'm guessing it's not happy with you using a base class and expects you to use the class itself - so although I've not tried this myself, I think the following should work:

    class TagType(DjangoObjectType):
        class Meta:
            model = FeedSource.tags.tag_model
            ...