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

Joe*_*nin 2 python django foreign-keys django-models django-admin

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

我的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)
Run Code Online (Sandbox Code Playgroud)

我的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)
Run Code Online (Sandbox Code Playgroud)

thingone如果use_thingone是真的,我该如何调整它以产生一个必需的外键字段?

Tho*_*zco 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!"))
Run Code Online (Sandbox Code Playgroud)