我有三个我想查询的课程。我想让数据库完成工作。是否可以在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.
答案 0 :(得分:2)
如果不加入这三个表,就无法做到这一点。
User.objects.filter(modela__name=u'William', modelb__category=u'Single',
modelc__alias=u'Bill')