我有两个模型,汽车和预订。汽车是预订模型中的ForeignKey字段。如果预订了汽车,则将其从汽车列表中删除。 预订汽车后,代码将更改为is_available_car = false。然后汽车没有显示在汽车列表视图中。但是 我面临的问题是:
请帮助我,如果汽车预订完成或我删除了预订。汽车的可用值将变为true !!
这些是我的模型和视图:
模型
class Booking(models.Model):
booking_name = models.CharField(max_length=240, null=False)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' )
book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car')
rental_price = models.IntegerField(blank=False, null=False)
times_pick = models.TimeField(blank=True)
is_approved = models.BooleanField(default=False)
def __str__(self):
return self.booking_name
def get_absolute_url(self):
return reverse("buggy_app:detail",kwargs={'pk':self.pk})
class Car(models.Model):
reg_no = models.CharField(max_length=16, unique=True)
model_year = models.DateField()
car_name =models.CharField(max_length=40)
car_image = models.ImageField(upload_to='cars', blank = True)
is_available_car = models.BooleanField(default = False)
def __str__(self):
return self.car_name
def get_absolute_url(self):
return reverse("buggy_app:details",kwargs={'pk':self.pk})
观看次数
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
return super(BookingView, self).form_valid(form)
success_url = reverse_lazy('index')
def get_context_data(self, **kwargs):
# kwargs['car'] is the car booking now!
try:
kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', ''))
except (Car.DoesNotExist, ValueError):
kwargs['car'] = None
return super(BookingView, self).get_context_data(**kwargs)
class CarListView(ListView):
context_object_name = 'cars'
model = models.Car
def get_queryset(self):
qs = super(CarListView, self).get_queryset()
qs = qs.filter(is_available_car=True)
return qs
答案 0 :(得分:0)
您可以创建一个信号处理程序,以监听pre_delete
模型的Booking
信号:请参见documentation。因此,每次删除预订时,都会调用您的信号处理程序,您将能够更新相应的汽车。
例如
@receiver(pre_delete, sender=Booking):
def update_car(sender, **kwargs):
car = sender.book_car
car.is_available = True
car.save()
然后确保您按照上述Django文档中的说明注册处理程序。
现在我不知道您所说的“预订完成时”是什么意思,但这听起来像Booking模型本身的一种方法:
def finish(self):
self.expired = True # You'd have to define what it means for a booking to be finished
car = self.book_car
car.is_available = True
car.save()