我在进行查询时遇到问题。在shell中,我一直都面临“用户”没有拆分错误。并想知道如何查询这些模型。
select i.id, i.name, i.email, i.memo, g.id, g.name, i.birthday, i.regdt, n.number, t.name, t.id
from webcontact_info as i
inner join webcontact_number as n on i.id = n.info_id
inner join webcontact_group as g on i.group_id = g.id
inner join webcontact_type as t on n.type_id = t.id;
此查询在mysql中。如何更改为Django的查询? 请帮助我。
这些是模型。py
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
答案 0 :(得分:0)
您可以仅将相关对象与对象一起使用。但也许您正在寻找select_related
。
它将返回选择其他相关对象数据的功能-将大大提高查询性能。
infos = Info.objects.select_related('user', 'group', 'user__number')
。