我有两个模型,分别是Booking和Confirmation,它们通过“预订”通过ForeignKey关系关联。我只想在我的详细信息视图中显示属性值为is_confirmed == True的预订。我真的不需要查询集,如果模板中的确认为True,我只想显示“预订”模型中的预订信息。
models.py:
class Booking(models.Model):
user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE)
expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings')
title = models.CharField(max_length=200, default='Video call with ..', null=True)
start_time = models.DateTimeField('Start time', null=True)
end_time = models.DateTimeField('End time', null=True)
notes = models.TextField('Notes', blank=True, null=True)
class Meta:
verbose_name = 'Booking'
verbose_name_plural = 'Bookings'
def get_absolute_url(self):
return reverse('booking:booking_detail', kwargs={"pk": self.pk})
class Confirmation(models.Model):
booking = models.ForeignKey(Booking, on_delete=models.CASCADE)
expert_confirming = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
is_confirmed = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('booking:booking_detail', kwargs={"pk": self.booking_id})
views.py:
class BookingDetailView(DetailView):
model = Booking
template = 'templates/booking_detail.html'
booking_detail.html:
<div class="container" id="booking_content">
<p>{{ booking.title }}</p>
<p>{{ booking.start_time }}</p>
<p>Booking request by: {{ booking.user }}</p>
<p>Expert requested: {{ booking.expert }}</p></div>
我不确定模板中的if语句如何引用这些相关模型以显示我想要的内容。
答案 0 :(得分:2)
我认为使用模型的方式必须对确认模型运行查询,以确定是否存在针对特定预订的确认。但是,为什么要有一个单独的确认模型呢?尝试仅将相关字段移入预订模型:
class Booking(models.Model):
user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE)
expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings')
title = models.CharField(max_length=200, default='Video call with ..', null=True)
start_time = models.DateTimeField('Start time', null=True)
end_time = models.DateTimeField('End time', null=True)
notes = models.TextField('Notes', blank=True, null=True)
is_confirmed = models.BooleanField(default=False) # just this field since you already have an expert.
这简化了事情,并减轻了数据库的负担。然后,您只能显示使用以下模板语言确认的预订:
{% if booking.is_confirmed %}
<div class="container" id="booking_content">
<p>{{ booking.title }}</p>
<p>{{ booking.start_time }}</p>
<p>Booking request by: {{ booking.user }}</p>
<p>Expert requested: {{ booking.expert }}</p>
</div>
{% else %}
...
{% endif %}
您可能有充分的理由使用单独的确认模型。如果是这样,那么这个答案是无关紧要的。如果没有,那么也许可以帮助您简化事情。