我有两个模特
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
BusinessHours表数据
id BID Rating Comment
1 1 3 Comment1
2 1 5 Comment2
3 2 4 Comment3
4 2 5 Comment4
然后结果应该在对象中:
BID Businame ContactPerson Rating Comment
1 First First 4 2
2 Second Second 4.5 2
我已多次尝试但我无法做到这一点.P
编辑:
today = datetime.datetime.today().weekday() + 1
BusinessHours表数据
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)
过滤来自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给出当天的价值。
答案 0 :(得分:0)
您可以使用annotation with aggregation:
from django.db.models import Count, Avg
qs = Business.objcts.annotate(comment_count=Count('businesscomment'),
avg_rating=Avg('businesscomment__rating'))
然后,在查询集中,您可以访问comment_count
或avg_rating
:
# I am using these fields in values_list for example
qs.values_list('BID', 'BusinessName', 'ContactPerson', 'comment_count', 'avg_rating')