Anand
Anand

Reputation:

help with complex join in Django ORM

class Domains(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length= 60)
    user = models.ManyToManyField("Users", blank=True, null=True)
    def __unicode__(self):
        return self.name

class Groups(models.Model):
    domain = models.ForeignKey(Domains)
    name = models.CharField(max_length=30)
    description = models.CharField(max_length= 60)
    def __unicode__(self):
        return self.name

class Users(models.Model):
    login = models.CharField(max_length=30, unique=True)
    group = models.ManyToManyField(Groups, blank=True, null=True)
    def __unicode__(self):
        return self.login

I have the model above. Needed some assistance working with Django ORM. How would I build a query the returns all the Group names that belong to only those Domains to which a User belongs

Upvotes: 3

Views: 1588

Answers (2)

Jarret Hardie
Jarret Hardie

Reputation: 97902

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.

Upvotes: 4

elo80ka
elo80ka

Reputation: 15805

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.

Upvotes: 2

Related Questions