KindOfGuy
KindOfGuy

Reputation: 3211

Django model ManytoMany getters

I wanted to get a list of objects associated to model A by ManyToMany with model B, e.g. diners (A) confirmed to attend a meal(B). But I'm not sure what getter I should use. I actually wanted to do this to show the associated objects in the admin panel. The method included beneath was one failed attempt I made.

class Meal(models.Model):
    diners = models.ManyToManyField(User, through='Attendance', related_name="eating", blank=True)

    def diners(self):
        return self.eating

Can you help? Thanks

Upvotes: 1

Views: 522

Answers (2)

Sectio Aurea
Sectio Aurea

Reputation: 393

I arrived at this page with the same problem as OP. I ended up simply removing the reference to the ManyToMany field in list_display in my admin model. The result: on the admin page for that app, under the ManyToMany field name, appeared a nicely formatted multi-selection list widget with the possible values for my ManyToMany relationship shown.

So the solution was to remove the reference in list_display and let Django handle it. This is with Django 1.4.3.

Upvotes: 0

okm
okm

Reputation: 23871

As ilvar suggested, remove diners method and use self.diners.all() to get objects inside Meal methods. related_name='eating' is for fetching attended meals of a user, reversely.

Upvotes: 1

Related Questions