[英]Queryset of the foreign key Django
I have the model: 我有这个型号:
class Cliente(Endereco):
email = models.EmailField()
nome = models.CharField(max_length=60)
class Compromisso(models.Model):
cliente = models.ForeignKey(Cliente)
data = models.DateField()
How can I get the Queryset of de Client Model with Compromisso.date ? 如何使用Compromisso.date获取de Client Model的Queryset?
A queryset of Clients by filtering by compromisso.date (you put "data", i assume "date", as your question): 通过compromis过滤的客户端查询集(您输入“数据”,我假设“日期”,作为您的问题):
class Cliente(Endereco):
email = models.EmailField()
nome = models.CharField(max_length=60)
class Compromisso(models.Model):
cliente = models.ForeignKey(Cliente)
date = models.DateField()
queryset: 查询集:
Cliente.objects.filter(compromisso_set__date=someDate)
Getting a Client and every date from associated "Compromisso"'s date is not possible without using .extra and doing your own sql. 如果不使用.extra并使用自己的sql,则无法从关联的“Compromisso”日期获取客户端和每个日期。 You can get them lazily as
aClient.compromisso_set.all().only('date')
for each Cliente (aClient) object. 你可以
aClient.compromisso_set.all().only('date')
像aClient.compromisso_set.all().only('date')
每个Cliente(aClient)对象一样aClient.compromisso_set.all().only('date')
。
I am not sure if I understood your question correctly. 我不确定我是否理解你的问题。 You could get a
queryset
for all the Cliente objects
and then iterate through them to get the Compromisso.date
; 你可以得到一个
queryset
所有Cliente objects
,然后遍历它们来获得Compromisso.date
; something on this line: 这条线上的东西:
queryset1=Clients.objects.all()
for cliente in queryset1:
queryset=cliente.compromisso_set.all() # return all the compromisso objects
# get all the date fields objects for all the query sets
for c in queryset:
date=c.data
Note: this is inefficient. 注意:这是低效的。 unless you want to filter on a particular date, you try what Luis suggested
除非您想要在特定日期过滤,否则请尝试Luis建议的内容
This helpe me: 这帮我:
clientes = Cliente.objects.filter(compromisso__data=data).distinct()
Thank you @Luis Masuelli 谢谢@Luis Masuelli
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.