对于两种不同类别的帐户,我有两种形式。我想根据预订的类别进行一些计算。
models.py
-
forms.py
class category1(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
contact = models.CharField(max_length=100)
email = models.CharField(max_length=100)
def __str__(self):
return self.name
class category2(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
contact = models.CharField(max_length=100)
email = models.CharField(max_length=100)
def __str__(self):
return self.name
class booking(models.Model):
booked_by = models.CharField(max_length=100)
amount = models.IntegerField()
Total = models.IntegerField()
def save(self, *args, **kwargs):
if self.booked_by == category1:(NEED HELP OVER HERE, what query should I use)
self.Total = self.amount * 2
if self.booked_by == category2:(NEED HELP OVER HERE, what query should I use)
self.Total = self.amount * 4
super(booking,self).save()
view.py
class bookingform(ModelForm):
class Meta:
model = booking
exclude = ('booked_by','Total')
如果按类别1进行预订,则进行一些计算。 如果按类别2进行预订,请进行一些计算。
答案 0 :(得分:1)
如果我们假设User
是标准的django用户模型,则可以这样做:
def save(self, *args, **kwargs):
if category1.objects.filter(user__username=self.booked_by).exists():
self.Total = self.amount * 2
if category2.objects.filter(user__username=self.booked_by).exists()
self.Total = self.amount * 4
super(booking,self).save()
但是最好将booked_by
定义为User
的外键。在这种情况下,您将获得数据库一致性:
class booking(models.Model):
booked_by = models.ForeignKey(User, on_delete=models.CASCADE)
amount = models.IntegerField()
Total = models.IntegerField()
def save(self, *args, **kwargs):
if category1.objects.filter(user=self.booked_by).exists():
self.Total = self.amount * 2
if category2.objects.filter(user=self.booked_by).exists()
self.Total = self.amount * 4
super(booking,self).save()
class bookings_create(LoginRequiredMixin,CreateView):
login_url = 'Mel:user_login'
form_class = bookingform
template_name = 'Mel/bookings_form.html'
def form_valid(self, form):
form.instance.booked_by = User.objects.get(username=self.request.user)
return super(bookings_create, self).form_valid(form)
答案 1 :(得分:0)
两个类别都具有相同的字段。应该有一个Category
模型并使用Foreign Key
关系。