2011-07-13 78 views
0

我認爲這可能比Django更多的SQL,但Django是我在工作。我想要做的是想出一個對象模型,可以有許多屬性,但每個對象僅限於1個屬性類型。使用unique_together約束Django的多對多關係

假設我們有3種物業類型:

  • is_cool
  • is_happy
  • is_mean

假設我有一個對象(myObject的),它可以有*(0-ALL)這些屬性適用於它,但只有其中的一個。

所以我覺得這是如下可圖示(請糾正我,如果我錯了):

Object MySQL Diagram

在Django中我與這個有點吃力約束。我希望它在db級別,即使用unique_together

這裏是我有什麼..

PROP_VALUE_CHOICES = (("URL", "url"), 
         ("Boolean", "bool"), 
         ("String", "char"), 
         ("Person", "person")) 

class PropertyType(models.Model): 
    name = models.CharField(max_length=32) 
    value_type = models.CharField(max_length=32, choices=PROP_VALUE_CHOICES) 

class Property(models.Model): 
    type = models.ForeignKey(PropertyType) 
    value = models.CharField(max_length=32) 

class MyObjectA(models.Model): 
    properties = models.ManyToManyField(Property, related_name="MyObjectA") 

class MyObjectB(models.Model): 
    properties = models.ManyToManyField(Property, related_name="MyObjectB") 

所以問題:

  1. 是上面的圖片來記錄我想要實現的正確途徑。
  2. 我的模型不完整 - 我缺少什麼以及在何處應用unique together約束對象名稱和屬性類型。

順便說一句 - 這類似於this post,但他們使用的,通過它我不知道我需要?

謝謝!

回答

0

萬一真的有人在尋找這個答案...

使用Abstract Base Class我創建了下面的結構應該工作。授予它不再完全代表圖片,但確實解決了問題。

PROP_VALUE_CHOICES = (("URL", "url"), 
         ("Boolean", "bool"), 
         ("String", "char"), 
         ("Person", "person")) 

class PropertyType(models.Model): 
    name = models.CharField(max_length=32) 
    value_type = models.CharField(max_length=32, choices=PROP_VALUE_CHOICES) 

class Property(models.Model): 
    type = models.ForeignKey(PropertyType, unique=True, related_name="%(app_label)s_%(class)s_related") 
    value = models.CharField(max_length=32) 

    class Meta: 
     abstract = True 

class ObjectAProperties(Property): pass 

class ObjectA(models.Model): 
    properties = models.ManyToManyField(Property, through="ObjectAProperties") 

class ObjectBProperties(Property): pass 

class ObjectB(models.Model): 
    properties = models.ManyToManyField(Property, through="ObjectBProperties") 

張貼在案件我在未來需要這個!