2012-03-14 169 views
1

我想知道如何對相關對象進行驗證。令我驚訝的是,我還沒有找到有關這方面的很多相關信息。Django模型 - 相關對象驗證

例如:

class Listing(models.Model): 
    categories = models.ManyToManyField('Category') 
    price_sale = models.DecimalField(max_digits=8, decimal_places=0, null=True) 
    price_rent = models.DecimalField(max_digits=8, decimal_places=0, null=True) 
    price_vacation = models.DecimalField(max_digits=8, decimal_places=0, null=True) 

class Category(models.Model): 
    value = models.CharField(max_length=32) 

class Image(models.Model): 
    listing = models.ForeignKey('Listing') 
    image = models.ImageField(upload_to=get_file_path) 
  • 我怎樣才能確保至少有一個category設置,沒有 重複的上市?
  • 如何確保如果其中一個categories爲'出售',則必須設置price_sale否則設置爲空?
  • 如何確保插入至少一個image而不是比說10張圖像多 ?

我在想這應該在模型中完成,以防我選擇從表單中輸入數據(類似解析feed),這是否正確?我嘗試過處理clean(),但是在讓我處理m2m關係之前需要一個PK。

獎勵問題:爲什麼我會選擇使用選項限制字段而不是使用FK進行限制?

回答

0

嘗試明確創建您的映射表,並讓您的ManyToMany關係轉到through此模型。由於它是一個正常的Django模型,因此您應該能夠在其clean方法中定義大部分驗證邏輯。

class Listing(models.Model): 
    categories = models.ManyToManyField('Category', through='CategoryListing') 
    price_sale = models.DecimalField(max_digits=8, decimal_places=0, null=True) 
    price_rent = models.DecimalField(max_digits=8, decimal_places=0, null=True) 
    price_vacation = models.DecimalField(max_digits=8, decimal_places=0, null=True) 

class Category(models.Model): 
    value = models.CharField(max_length=32) 

class CategoryListing(models.Model): 
    category = models.ForeignKey(Category) 
    listing = models.ForeignKey(Listing) 

    def clean(self): 
     # validation logic 

https://docs.djangoproject.com/en/1.3/topics/db/models/#intermediary-manytomany

+0

這會更用於驗證有關'本身連接錶行,而不是listing'沒有?我想避免在沒有至少一個m2m關係的情況下插入「列表」。 – RS7 2012-03-14 14:40:08