我有一个带有外键的RelationType模型:
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 :(得分:0)
我提出了一个非常丑陋的解决方案(如果有人找到更好的解决方案,我会很高兴。)
我先生成灯具:
k
然后我使用一些UNIX魔法来删除“自我”关系:
O(nm)
对于对UNIX魔术的好奇,我用另一个任意字符翻译新行字符,因为./manage.py dumpdata --indent 4 --natural-primary --natural-foreign \
myapp.relationtype > fixtures/initial_relationtypes.json
不能做多行正则表达式。
然后我可以先用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
灯具加载两个灯具:
sed