【发布时间】:2016-05-17 04:31:36
【问题描述】:
我有两个模型
class Business(models.Model):
BID = models.IntegerField(primary_key=True, default=datetime.now().strftime("%d%y%H%S%m%M%f"))
BusinessName = models.CharField(max_length=150)
ContactPerson = models.CharField(max_length=50)
class BusinessComment(models.Model):
BID = models.ForeignKey(Business, blank=True, null=True)
Rating = models.IntegerField(blank=True, null=True)
Comment = models.TextField(blank=True, null=True)
class BusinessHours(models.Model):
BID = models.ForeignKey(Business, blank=True, null=True)
Day = models.IntegerField(blank=True, null=True)
StartHour = models.CharField(max_length=8, blank=True, null=True)
EndHour = models.CharField(max_length=8, blank=True, null=True)
我想访问两个模型的值以下的单个对象。这个概念是左外连接,但我可以在具有以下所有值的单个对象中实现。
BID,BusinessName,ContactPerson,AVG(Rating),Count(Number of Comment) (Condition is Business.BID = BusinessComment.BID)
业务表数据
BID BusinessName ContactPerson
1 First First
2 Second Second
营业时间表数据
id BID Rating Comment
1 1 3 Comment1
2 1 5 Comment2
3 2 4 Comment3
4 2 5 Comment4
那么结果应该在 Object As 中:
BID Businame ContactPerson Rating Comment
1 First First 4 2
2 Second Second 4.5 2
我尝试了很多次,但我无法做到。P
编辑:
today = datetime.datetime.today().weekday() + 1
营业时间表数据
id BID Day Stathours EndHour
145 1 1 12:00am 12:00am
146 1 2 Closed Closed
147 1 3 12:00am 12:00am
148 1 4 Closed Closed
149 1 5 12:00am 12:00am
150 1 6 12:00am 12:00am
151 1 7 12:00am 12:00am
152 2 1 12:00am 12:00am
153 2 2 12:00am 12:00am
154 2 3 12:00am 12:00am
155 2 4 12:00am 12:00am
156 2 5 12:00am 12:00am
157 2 6 12:00am 12:00am
158 2 7 12:00am 12:00am
现在我想使用 filter(BusinessHours.Day = today) 和 annotate 过滤来自 BusinessHours 的数据。所以输出将如下所示。
BID Businame ContactPerson Rating Comment StartHour EndHours
1 First First 4 2 12:00am 12:00pm
2 Second Second 4.5 2 12:00am 12:00pm
StartHour 和 EndHour 是当前日期的值。
【问题讨论】:
标签: sql django database left-join