我有customer
模型
Name, Email, Phone, State
A, Aemail, Apohone, Astate
A, Bemail, Apohone, Astate
A, Cemail, Apohone, Astate
表示一位客户有多封电子邮件。 这就是我想要从查询中得到的结果。
[{A, Aphone, Astate, [Aemail, Bemail, Cemail]},
{....},
]
Customers.objects.filter(**params).values_list('phone', 'name').distinct()
Thougts?
答案 0 :(得分:1)
您描述的架构是次优的。当仅更新/删除某些用户数据时,使用此模式将导致一致性问题。
如果您希望Customer
拥有多个email
,那么创建单独的Email
模型或使用数组字段会更明智。
class Customer(models.Model):
name = models.CharField(max_length=50)
class CustomerEmail(models.Model):
customer = models.ForeignKey(Customer, related_name='emails')
email = models.EmailField()
现在,您可以轻松进行所需的查询。
customers = Customer.objects.select_related('emails')
收到他们的电子邮件:
for email in customers.emails:
print(email.email)