问题描述
我有以下模型,我正在努力解决如何做后退关系。我想要一个不同的CostRate查询,显示与特定SalesEvent相关联的系统。 CostFixedList具有在不同日期发生的所有销售。
所以我会过滤特定SalesEvent的CostFixedList,创建一个[distinct]成本率的列表,然后将其与CostRate模型相匹配。 / p>
我可以在SQL中轻松实现,但是不能在ORM中如何做[甚至开始]。
class SalesEvent(models.Model):
event_type = models.ForeignKey(EventType,verbose_name =Event Type)
retailer = models .ForeignKey(Retailer,verbose_name =Retailer)
....
class CostRate(models.Model):
cost_item = models.ForeignKey(CostItem,verbose_name =项目)
valid_from = models.DateField(From)
valid_till = models.DateField(Till)
unit_amount = models.DecimalField(Price per Unit,max_digits = 5 ,decimal_places = 2)
class CostFixedList(models.Model):
sales_event = models.ForeignKey(SalesEvent)
cost_rate = models.ForeignKey(CostRate)
units = models.IntegerFi eld()
dating = models.ForeignKey(Appointment,null = True,blank = True)
看起来好像你在SalesEvent和CostRate之间有一个隐含的ManyToMany关系,通过表作为CostFixedList。
所以,如果你明确表达,你可以通过这种关系直接查询,而不用做任何聪明的事情。只需将其添加到您的CostRate模型中(不需要模式更改):
sales_events = models.ManyToManyField(SalesEvent,through ='CostFixedList ')
现在你可以做:
my_sales_event.costrates.all()
I have the following models and I'm trying to work out how to do backward relationships.
I want a distinct CostRate queryset showing which costrates are associated with a particular SalesEvent. The CostFixedList has all the sales that occurred on the different days.
So I'd filter the CostFixedList for a particular SalesEvent, create a list of the [distinct] cost rates it has and then match that up with the CostRate model.
I could do this easily in SQL, but can't get my head around how to do it [or even start] in ORM.
class SalesEvent(models.Model):
event_type = models.ForeignKey(EventType, verbose_name="Event Type")
retailer = models.ForeignKey(Retailer, verbose_name="Retailer")
....
class CostRate(models.Model):
cost_item = models.ForeignKey(CostItem, verbose_name="Item")
valid_from = models.DateField("From")
valid_till = models.DateField("Till")
unit_amount = models.DecimalField("Price Per Unit", max_digits=5, decimal_places=2)
class CostFixedList(models.Model):
sales_event = models.ForeignKey(SalesEvent)
cost_rate = models.ForeignKey(CostRate)
units = models.IntegerField()
appointment = models.ForeignKey(Appointment, null=True, blank=True)
It looks to me as if you have an implied ManyToMany relationship between SalesEvent and CostRate, with the through table as CostFixedList.
So, if you make that explicit, you can query directly via that relationship without having to do anything clever. Just add this to your CostRate model (no schema changes required):
sales_events = models.ManyToManyField(SalesEvent, through='CostFixedList')
Now you can do:
my_sales_event.costrates.all()
这篇关于反向关系和不同的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!