[Django]-Help with complex join in Django ORM

4👍

I second elo80ka’s comment about using singular names for your models. To filter the groups by domain and user, try:

Groups.objects.filter(domain__user=u)

This will perform the appropriate join across the many-to-many. As written, the query will return group objects. If you want the name property only, then append the .values_list('name', flat=True) to the query as elo80ka suggests.

2👍

You should probably use singular names for your model classes. For example, I’d rewrite the models as:

class Domain(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length= 60)
    user = models.ManyToManyField('User', blank=True, null=True)

    def __unicode__(self):
            return self.name

class Group(models.Model):
    domain = models.ForeignKey(Domain, related_name='groups')
    name = models.CharField(max_length=30)
    description = models.CharField(max_length= 60)

    def __unicode__(self):
            return self.name

class User(models.Model):
    login = models.CharField(max_length=30, unique=True)
    group = models.ManyToManyField(Group, related_name='users', blank=True, null=True)

    def __unicode__(self):
            return self.login

Since you have users directly related to groups, you don’t need to involve domains at all. To fetch all group names for a particular user, you’d do:

Group.objects.filter(users__pk=...).values_list('name', flat=True)

Replace ‘…’ with the ID of the user you’re interested in.

Leave a comment