2012-04-01 4 views
2

私のモデルの1つでは、別のブールモデルフィールドがtrueの場合にのみ外部キーオブジェクトが必要になります。このように動作するように管理サイトを設定するにはどうすればよいですか?他のモデルフィールドが真である場合にのみ、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) 

そして、私の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) 

私はuse_thingoneがtrueの場合にのみthingone必要な外部キーフィールドを作るために、これを調整するにはどうすればよいですか?

答えて

5

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

ThingTwoのフォームを作成し、モデルのclean()メソッドで必要なものをチェックします。ここで

モデル用のフォーム作成している - https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelformを、モデル管理者のためのカスタムフォームを使用して - あなたが実際には、モデルのcleanメソッドオーバーライドする必要がhttps://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin

関連する問題