Django - 坚持创建定价系统
Django - Stuck On Creating a Pricing System
I am making a "booking airbnb" website.
在我的公寓详细信息页面上,我有一个 JQuery UI 日期选择器日历,用户可以使用它输入预订的开始和结束日期。
一旦完成并且用户提交了我想刷新整个网站的表单,并且在刷新时显示用户之前选择的日期,以及每天的价格和总价。
在我创建的模型中:
models.py:
class Apartment(models.Model):
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
apartment_price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
size = models.IntegerField()
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
list_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
class ApartmentImages(models.Model):
apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
def __str__(self):
return self.image.url
class ApartmentPrices(models.Model):
apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price")
price_start_date = models.DateField(blank=True, null=True)
price_end_date = models.DateField(blank=True, null=True)
price = models.IntegerField()
def __str__(self):
return self.apartment.title
class Reservation(models.Model):
apartment = models.ForeignKey(Apartment, related_name='reservations',
on_delete=models.CASCADE, blank=True, null=True)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
name = models.CharField(default="", max_length=200)
def __str__(self):
return self.name
这是我目前的看法。我尝试了很多不同的东西,但我仍然坚持这应该如何工作的逻辑。
这是我的观点:
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
prices = ApartmentPrices.objects.filter(apartment__pk=apartment_id)
context = {}
context['apartment'] = apartment
context['prices'] = prices
# svi datumi za cijene
price_dates = []
for start, end, price in prices.values_list('price_start_date', 'price_end_date', 'price'):
while start <= end:
price_dates.append(start.strftime('%-d-%m-%Y'))
price_dates.append(price)
start += datetime.timedelta(days=1)
unavailable = []
for start, end in apartment.reservations.values_list('start_date', 'end_date'):
while start <= end:
unavailable.append(start.strftime('%-d-%m-%Y'))
start += datetime.timedelta(days=1)
form = ReservationForm()
context['unavailable_dates'] = json.dumps(unavailable)
context['form'] = form
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return render(request, "booking/apartment.html", context)
return render(request, 'booking/apartment.html', context)
谁能帮我弄清楚比较用户选择的日期与数据库中的价格日期并获取价格的最佳方法是什么?
非常感谢,一直卡在这个问题上一段时间了。
您可以为 Appartment 提供一种方法来获取给定日期对象介于开始日期和结束日期之间的价格。
(未经测试)
...
from django.db.models import Q
class Apartment(models.Model):
...
def price_by_date(self, date_obj):
"""returns the first price with date_obj is between start and end date
Args:
date_obj(datetime.date): the date of the price you want
Returns:
ApartmentPrices: first valid price found
"""
# self.price is a back reference to all prices with self as apartment
# you named it by giving related_name="price" in ApartmentPrices.apartment
return self.price.filter(
Q(price_start_date__lte=date_obj) & Q(price_end_date__gte=date_obj)
).first()
...
在视图中你应该可以做到:
...
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
date_price = apartment.price_by_date(datetime.date(2019, 10,18))
# date_price.price would be the integer
...
更多信息:
Q - queries 用于将两个查询(开始+结束)合并为一个查询。
I am making a "booking airbnb" website.
在我的公寓详细信息页面上,我有一个 JQuery UI 日期选择器日历,用户可以使用它输入预订的开始和结束日期。
一旦完成并且用户提交了我想刷新整个网站的表单,并且在刷新时显示用户之前选择的日期,以及每天的价格和总价。
在我创建的模型中:
models.py:
class Apartment(models.Model):
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
apartment_price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
size = models.IntegerField()
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
list_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
class ApartmentImages(models.Model):
apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
def __str__(self):
return self.image.url
class ApartmentPrices(models.Model):
apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price")
price_start_date = models.DateField(blank=True, null=True)
price_end_date = models.DateField(blank=True, null=True)
price = models.IntegerField()
def __str__(self):
return self.apartment.title
class Reservation(models.Model):
apartment = models.ForeignKey(Apartment, related_name='reservations',
on_delete=models.CASCADE, blank=True, null=True)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
name = models.CharField(default="", max_length=200)
def __str__(self):
return self.name
这是我目前的看法。我尝试了很多不同的东西,但我仍然坚持这应该如何工作的逻辑。
这是我的观点:
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
prices = ApartmentPrices.objects.filter(apartment__pk=apartment_id)
context = {}
context['apartment'] = apartment
context['prices'] = prices
# svi datumi za cijene
price_dates = []
for start, end, price in prices.values_list('price_start_date', 'price_end_date', 'price'):
while start <= end:
price_dates.append(start.strftime('%-d-%m-%Y'))
price_dates.append(price)
start += datetime.timedelta(days=1)
unavailable = []
for start, end in apartment.reservations.values_list('start_date', 'end_date'):
while start <= end:
unavailable.append(start.strftime('%-d-%m-%Y'))
start += datetime.timedelta(days=1)
form = ReservationForm()
context['unavailable_dates'] = json.dumps(unavailable)
context['form'] = form
if request.method == 'GET':
form = ReservationForm()
elif request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
reservation = form.save(commit=False)
reservation.apartment = apartment
reservation.save()
form.save()
return render(request, "booking/apartment.html", context)
return render(request, 'booking/apartment.html', context)
谁能帮我弄清楚比较用户选择的日期与数据库中的价格日期并获取价格的最佳方法是什么?
非常感谢,一直卡在这个问题上一段时间了。
您可以为 Appartment 提供一种方法来获取给定日期对象介于开始日期和结束日期之间的价格。 (未经测试)
...
from django.db.models import Q
class Apartment(models.Model):
...
def price_by_date(self, date_obj):
"""returns the first price with date_obj is between start and end date
Args:
date_obj(datetime.date): the date of the price you want
Returns:
ApartmentPrices: first valid price found
"""
# self.price is a back reference to all prices with self as apartment
# you named it by giving related_name="price" in ApartmentPrices.apartment
return self.price.filter(
Q(price_start_date__lte=date_obj) & Q(price_end_date__gte=date_obj)
).first()
...
在视图中你应该可以做到:
...
def apartment_view(request, apartment_id):
reservation = Reservation.objects.filter(apartment__pk=apartment_id)
apartment = get_object_or_404(Apartment, pk=apartment_id)
date_price = apartment.price_by_date(datetime.date(2019, 10,18))
# date_price.price would be the integer
...
更多信息:
Q - queries 用于将两个查询(开始+结束)合并为一个查询。