Getting the first item item in a many-to-many relation in Django

11,703

Solution 1

Django doesn't pay attention to the order of the calls to add. The implicit table Django has for the relationship is something like the following if it was a Django model:

class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)

Obviously, there's nothing there about an "order" or which you should come first. By default, it will probably do as you describe and return the lowest pk, but that's just because it has nothing else to go off of.

If you want to enforce an order, you'll have to use a through table. Basically, instead of letting Django create that implicit model, you create it yourself. Then, you'll add a field like order to dictate the order:

class GroupMembers(models.Model):
    class Meta:
        ordering = ['order']

    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)
    order = models.PositiveIntegerField(default=0)

Then, you tell Django to use this model for the relationship, instead:

class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person, through='GroupMembers')

Now, when you add your members, you can't use add anymore, because additional information is need to complete the relationship. Instead, you must use the through model:

prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, order=1)
prs = Person.objects.create(name="Dick")
GroupMembers.objects.create(person=prs, group=grp, order=2)
prs = Person.objects.create(name="Harry")
GroupMembers.objects.create(person=prs, group=grp, order=3)

Then, just use:

Group.objects.get(id=1).members.all()[0]

Alternatively, you could simply add a BooleanField to specify which is the main user:

class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)
    is_main_user = models.BooleanField(default=False)

Then, add "Tom" like:

prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, is_main_user=True)

And finally, retrieve "Tom" via:

Group.objects.get(id=1).members.filter(is_main_user=True)[0]

Solution 2

Relational database don't have any notion of ordering, by default. There's no such thing as "first". You need to add an explicit "order" field which keeps the order, and order by it.

Solution 3

You were pretty close:

Group.objects.get(id=1).members.all()[0]

(But as Alex Gaynor says in his answer, for predictable behaviour you need a proper field to sort on)

Share:
11,703
Mridang Agarwalla
Author by

Mridang Agarwalla

I'm a software developer who relishes authoring Java and Python, hacking on Android and toying with AppEngine. I have a penchant for development and a passion for the business side of software. In between all the work, I contribute to a number of open-source projects, learn to master the art of cooking Asian cuisine and try to stay sane while learning to fly my Align Trex-600 Nitro Heli.

Updated on July 10, 2022

Comments

  • Mridang Agarwalla
    Mridang Agarwalla almost 2 years

    I have two models in Django linked together by ManyToMany relation like this:

    class Person(models.Model):
        name = models.CharField(max_length=128)
    
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(Person)
    

    I need to get the main person in the group which is the first person in the group. How can I get the first person?

    Here's how I'm adding members:

    grp = Group.objects.create(name="Group 1")
    grp.save()
    prs = Person.objects.create(name="Tom")
    grp.members.add(prs) #This is the main person of the group.
    prs = Person.objects.create(name="Dick")
    grp.members.add(prs)
    prs = Person.objects.create(name="Harry")
    grp.members.add(prs)
    

    I don't think I need any additional columns as the id of the table group_members is a running sequence right.

    If I try to fetch the main member of the group through Group.objects.get(id=1).members[0] then Django says that the manager is not indexable.

    If I try this Group.objects.get(id=1).members.all().order_by('id')[0], I get the member with the lowest id in the Person table.

    How can I solve this?

    Thanks