仅当另一个模型字段为true时,才需要管理站点中的模型字段

时间:2012-04-01 13:48:04

标签: python django django-models django-admin foreign-keys

在我的一个模型中,我希望只有在另一个布尔模型字段为真时才需要外键对象。如何配置管理站点以这种方式运行?

我的models.py包含:

from django.db import models

class ThingOne(models.Model):
    name = models.CharField(max_length=100)

class ThingTwo(models.Model):
    name = models.CharField(max_length=100)
    use_thingone = models.BooleanField()
    thingone = models.ForeignKey(ThingOne, blank=True, null=True)

我的admin.py包含:

from myapp.models import ThingOne
from myapp.models import ThingTwo
from django.contrib import admin

admin.site.register(ThingOne)
admin.site.register(ThingTwo)

如果thingone为真,我如何调整此选项以使use_thingone成为必需的外键字段?

2 个答案:

答案 0 :(得分:5)

您实际上只需要覆盖模型的clean方法:

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.db import models

class ThingTwo(models.Model):
    #Your stuff

    def clean(self):
        """
        Validate custom constraints
        """
        if self.use_thingone and self.thingone is None:
            raise ValidationError(_(u"Thing One is to be used, but it not set!"))

答案 1 :(得分:1)

为ThingTwo创建表单,并在模型的clean()方法中检查您需要的内容。

以下是为模型创建表单 - https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform并使用自定义表单进行模型管理 - https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin

相关问题