Question

I have three classes I'd like to query. I would like to let the database do the work. Would it be possible to run a single query on the User object to get all the related fields that match? I am trying to avoid joining the three tables in my code. If I were to do it in the code, I would query all three classes then eliminate the duplicates while keeping the matches.

Query: Get all users whose name contains "William", category is "Single" and alias is "Bill". 

class ModelA(models.Model):
    user = models.ForeignKey(User,related_name="%(class)s",null=False)
    name = models.CharField(max_length=70)

    def __unicode__(self):
        return u'%s' % (self.name)

class ModelB(models.Model):
    user = models.ForeignKey(User,related_name="%(class)s",null=False)
    category = models.CharField(max_length=70)

    def __unicode__(self):
        return u'%s' % (self.category)

class ModelC(models.Model):
    user = models.ForeignKey(User,related_name="%(class)s",null=False)
    alias = models.CharField(max_length=70)

    def __unicode__(self):
        return u'%s' % (self.alias)

Note: this is an example only, and I am not looking to combine all the info in a single table.
Was it helpful?

Solution

You can't do this without joining the three tables.

User.objects.filter(modela__name=u'William', modelb__category=u'Single',
  modelc__alias=u'Bill')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top