更新时间:2022-12-05 17:33:50
您可以在 T_Return
模型,并将复制值从 T_Sales
保存:
You can create separate field in T_Return
model and copy value from T_Sales
on save:
class T_Sales(models.Model):
product = models.ForeignKey(P_Product)
sales_quantity = models.IntegerField()
def __unicode__(self):
return str(self.id)
class T_Return(models.Model):
sales_id = models.ForeignKey(T_Sales)
sales_quantity = models.IntegerField(editable=False)
return_quantity = models.IntegerField()
def __unicode__(self):
return self.description
def save(self, *args, **kwargs):
if not self.sales_quantity:
self.sales_quantity = self.sales_id.sales_quantity
supr(T_Return, self).save(*args, **kwargs)
该方法的优点:
T_Sales
的附加查询。T_Sales
only on (first) save.该方法的缺点是:
- 您正在数据库中存储值
- 如果 T_Sales
对象中的值将更改,则 T_Return
中的值不会自动更改(可以通过保存 T_Sales
的简单触发来修复,但只能在django ORM内)
Cons of that method:
- You're storing value in database twice
- If value in T_Sales
object will change, value in T_Return
won't be changed automatically (that can be fixed by simple trigger on save of T_Sales
, but only inside django ORM)
如果你不想创建一些验证,你可以覆盖模型的 clean
方法,并在这里做比较,如果有什么问题,你应该抛出$ $ C> ValidationError 。示例:
If you wan't to create some validation, you can override model's clean
method and do your comparsion here, if there is something wrong, you should throw ValidationError
. Example:
from django.core.exceptions import ValidationError
class T_Return(models.Model):
# ......
def clean(self):
if self.return_quantity > self.sales_quantity:
raise ValidationError("You can't return more than it was bought")
return super(T_Return, self).clean()
您还可以将错误分配给 return_quantity
或 sales_quantity
字段,只需将表单'field_name':error
转换为验证错误:
You can also assign error to return_quantity
or to sales_quantity
field, just pass dict in form 'field_name': error
into validation error:
raiseValidationError({'return_quantity': _('You can't return more than it was bought.')}
将errot分配给 return_quantity
和 sales_quantity
将会显示两次错误。
Assigning that errot both to return_quantity
and sales_quantity
will show that error twice.