2017-08-12 61 views
0

我有一個外鍵RelationType模型本身:Django的序列化:外鍵同型號

class TypeManager(models.Manager): 
    def get_by_natural_key(self, slug): 
     return self.get(slug=slug) 

class RelationType(models.Model): 
    name = models.CharField(_(u"Name"), max_length=100) 
    slug = models.SlugField(_(u"Slug"), max_length=100, unique=True) 
    inverse_relation = models.ForeignKey(
     'RelationType', verbose_name=_(u"Inverse relation"),   
     blank=True, null=True) 
    objects = TypeManager() 

    def natural_key(self): 
     return (self.slug,) 

一旦連載它會產生這樣的JSON的:

[{ 
    "fields": { 
     "name": "Has got", 
     "inverse_relation": [ 
      "is_in" 
     ], 
     "slug": "has_got" 
    }, 
    "model": "myapp.relationtype" 
}, 
{ 
    "fields": { 
     "name": "Is in", 
     "inverse_relation": [ 
      "has_got" 
     ], 
     "slug": "is_in" 
    "model": "myapp.relationtype" 
}] 

這在邏輯上不適合Django:

DeserializationError: Problem installing fixture 'myfixture.json': RelationType matching query does not exist. 

有沒有一種方法可以明智地管理這個問題?

+0

也許不相關的問題,但外鍵應該使用'''self'''定義。請參閱[doc](https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey)。 – mimo

+0

確實沒有解決問題。但是,謝謝你的評論。在使用模型的子類時,使用'self''很有趣。 –

回答

0

我想出了一個非常醜陋的解決方案(我會很高興,如果有人來一個更好的一個)。

我第一次產生夾具:

./manage.py dumpdata --indent 4 --natural-primary --natural-foreign \ 
    myapp.relationtype > fixtures/initial_relationtypes.json 

然後我用一些UNIX魔法刪除「自我」的關係:

cat fixtures/initial_relation_types.json | tr '\n' '\r' | \ 
    sed -e 's/"inverse_relation": *\[\r *\"[-_a-z0-9]*\" *\r *\]/"inverse_relation": null/g' | \ 
    tr '\r' '\n' > fixtures/initial_relation_type-norel.json 

對於好奇UNIX魔術,我翻譯了新行字符另一個任意字符,因爲sed不能做多行正則表達式。

然後,我可以用norel夾具首先加載兩場比賽:

./manage.py loaddata fixtures/initial_relation_type-norel.json 
./manage.py loaddata fixtures/initial_relation_type.json