question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Django: Make m2m through table fields available on edges

See original GitHub issue

When a DjangoConnectionField traverses a many-to-many field it would be nice to have the option to expose the fields of any through-table on the edges of the relationship.

[As much a note for myself as a feature request]

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:21
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

5reactions
Eraldocommented, May 23, 2020

Any updates on this? Still looking forward to automatic through edges. 😃

4reactions
McPocommented, Sep 12, 2019

So I’ve found a way of implementing this using annotations

class Member(DjangoObjectType):
     class Meta:
         model = models.Member

     channels = graphene.ConnectionField('api.graphql.MemberToChannelConnection')

     def resolve_channels(instance, info):
         return instance.channels.annotate(broadcaster=F('memberships__broadcaster'))

class Channel(DjangoObjectType):
     class Meta:
         model = models.Channel

     members = graphene.ConnectionField('api.graphql.ChannelToMemberConnection')

    def resolve_members(instance, info):
        return instance.members.annotate(broadcaster=F('channel_memberships__broadcaster'))


class ChannelMembershipEdge:
    broadcaster = graphene.NonNull(graphene.Boolean)

    def resolve_broadcaster(instance, info):
        return instance.node.broadcaster

class ChannelToMemberConnection(graphene.Connection):
    class Meta:
        node = Member
    class Edge(ChannelMembershipEdge):
        pass

class MemberToChannelConnection(graphene.Connection):
    class Meta:
        node = Channel
    class Edge(ChannelMembershipEdge):
        pass

I have also created a custom connection field to add annotations

from functools import partial
class AnnotateConnectionField(graphene.ConnectionField):
    def __init__(self, type, annotate_fields, *args, **kwargs):
        super().__init__(type, *args, **kwargs)
        self.annotate_fields = annotate_fields

    def get_resolver(self, parent_resolver):
        resolver = super(graphene.ConnectionField, self).get_resolver(parent_resolver)
        patched_resolver = lambda *args, **kwargs: resolver(*args, **kwargs).annotate(**self.annotate_fields)
        return partial(self.connection_resolver, patched_resolver, self.type)

So the above becomes

class Member(DjangoObjectType):
     class Meta:
         model = models.Member

     channels = AnnotateConnectionField('api.graphql.MemberToChannelConnection', dict(broadcaster=F('memberships__broadcaster')))

class Channel(DjangoObjectType):
     class Meta:
         model = models.Channel

     members = AnnotateConnectionField('api.graphql.ChannelToMemberConnection', dict(broadcaster=F('channel_memberships__broadcaster')))

class ChannelMembershipEdge:
    broadcaster = graphene.NonNull(graphene.Boolean)

    def resolve_broadcaster(instance, info):
        return instance.node.broadcaster

class ChannelToMemberConnection(graphene.Connection):
    class Meta:
        node = Member
    class Edge(ChannelMembershipEdge):
        pass

class MemberToChannelConnection(graphene.Connection):
    class Meta:
        node = Channel
    class Edge(ChannelMembershipEdge):
        pass

I also attempted to have the two Connection classes autogenerated within the connection field. So you basically pass in the the node value and it would generate the class for you. However because graphene.Connection.Meta.node does not support lazy loading the class, I got into an issue with circular dependencies that I was unable to resolve. Im sure theres a lot more magic that could be done too. One potential issue with this approach is that I doubt it will work if the Through tables “metadata” is a FK to another object, as Im not sure annotation would support that.

Anyway this is a sufficient enough solution for myself for now

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to order by a field from the `through` table for a M2M ...
I suggest you use a Prefetch object. class PinboardDetailView(DetailView): model = Pinboard queryset = Pinboard.objects.prefetch_related( ...
Read more >
Switching model on an M2M field results in a broken db (no ...
After changing to models.ManyToManyField(Bar) and running makemigrations and migrate , I can see (using ./manage.py dbshell ) that the schema for the m2m...
Read more >
Adding a through table to existing M2M fields - David - Medium
In this post we'll explore this scenario and show how this can be resolved with step by step examples.
Read more >
Tips for Using Django's ManyToManyField - REVSYS
The invisible "through" model that Django uses to make many-to-many relationships work requires the primary keys for the source model and the ...
Read more >
Queries & ObjectTypes - Graphene-Python
If you only want a subset of fields to be present, you can do so using fields or exclude . It is strongly...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found