2011-07-13 8 views
0

これはDjangoよりもSQLかもしれませんが、Djangoは私が取り組んでいることです。私がやっていることは、多くのプロパティがオブジェクトごとに1つのプロパティタイプに制限されています。unique_togetherを使ったdjangoの多対多リレーションシップ

は、我々は3つのプロパティタイプを持っていると言う:

  • is_cool
  • is_happy
  • is_mean

私は*を持つことができるオブジェクト(MyObjectに)(0-すべて)のを持っていると仮定しますこれらのプロパティはそれに適用されますが、それぞれのプロパティは1つのみです。

だから私は(私が間違っている場合は、私を修正してください)以下のようにこれが図解されていると思う:

ジャンゴで

Object MySQL Diagram

私はこの制約をstugglingています。 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という制約が適用されます。

BTW - これは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") 

私は今後これが再び必要になります!

関連する問題