0

我想查询三个课程。我想让数据库完成这项工作。是否可以对 User 对象运行单个查询以获取所有匹配的相关字段?我试图避免在我的代码中加入三个表。如果我要在代码中执行此操作,我将查询所有三个类,然后在保留匹配项的同时消除重复项。

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.
4

1 回答 1

3

如果不加入这三个表,您将无法执行此操作。

User.objects.filter(modela__name=u'William', modelb__category=u'Single',
  modelc__alias=u'Bill')
于 2012-03-11T04:59:36.807 回答