2012-04-01 33 views
2

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

我的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是真的吗?

回答

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!")) 
相关问题