【发布时间】:2021-10-01 21:30:54
【问题描述】:
我需要在一个模板中获取两个模型数据。如果我在一个元组或列表中没有联合这两个模型进行循环,如您所知,我会得到太多循环信息,所以我需要您的帮助。
这是我尝试过的,但没有奏效......
@login_required
def my_hotels(request):
hotels_info = AddHotelStep1.objects.all()
hotels_info_2 = AddHotelStep2.objects.all()
info = dict()
info['hotels_info'] = hotels_info
info['hotels_info_2'] = hotels_info_2
context = {'info':info,}
return render(request, 'myhotels.html', context)
这是我的模板:
{% for hotel in info %}
{% if user.is_authenticated and hotel.customer == user %}
{{hotel.hotel_name}}
{% with ''|center:hotel.star as range %}
{% for i in range %}
<span class="fa fa-star checked"></span>
{% endfor %}
{% endwith %}
{{hotel.hotel_type}}
{{hotel.short_description}}
{% endif %}
{% endfor %}
这是我的模型:
class AddHotelStep1(models.Model):
customer = models.ForeignKey(Account, on_delete=models.CASCADE)
hotel_name = models.CharField(max_length=50)
short_description = models.TextField(max_length=250)
long_description = models.TextField(max_length=2000)
HOTEL_STAR = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5')
)
star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True)
picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/default.jpg", blank=True)
class AddHotelStep2(models.Model):
hotel_name_2 = models.ForeignKey(AddHotelStep1, on_delete=models.CASCADE)
HOTEL_TYPE = (
('Single', 'Single'),
('Double', 'Double'),
)
hotel_type = models.TextField(max_length=10, choices=HOTEL_TYPE)
我会得到任何解决它的建议。
【问题讨论】:
-
请不要制作像
AddHotel这样的模型,模型不应该针对用例定制:它应该针对如何在用例不知情的上下文中表示数据而定制。 -
好的,知道了,谢谢。
标签: python-3.x django django-models django-views django-templates