Search code examples
pythondjangodjango-modelsmany-to-many

How to return fields of both related models in a Django ManyToMany relation?


I have two models:

class P(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...

class F(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...
    p = models.ManyToManyField(P)

I need a query like this:

SELECT p.name, f.name
FROM f
JOIN f_p ON f.id = f_p.f_id
JOIN p ON p.id= f_p.p_id

I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names.

In psql the query works like I need. How can I do this in Django?


Solution

  • Try values_list docs

    F.objects.values_list('name', 'p__name')