且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django Admin - 如何从其他表中拖动模型默认字段值

更新时间: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 的附加查询。

  • 在管理员的详细视图中轻松显示价值

  • It will trigger additional query to T_Sales only on (first) save.
  • It is easy to display value in admin's detail view

该方法的缺点是:
- 您正在数据库中存储值
- 如果 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.