簡體   English   中英

如何在Django中的ContentType外鍵上使用get_by_natural_key()加載數據夾具?

[英]How to load a data fixture with get_by_natural_key() on ContentType foreign key in Django?

我在為使用ContentType外鍵的模型加載外部數據夾具時遇到問題。

我在模型中使用經理,就像文檔所說的那樣。 不幸的是,盡管文檔討論了ContentType外鍵上的get_by_natural_key方法的重要性,但隨后它啟動了另一個示例。 我很難弄清經理的模樣。 我最好的猜測是再次使用get_by_natural_key並分配app_labelmodel查找,但是我可能會離開。

# models.py 
from django.db import models 
from django.contrib.contenttypes.models import ContentType 
from django.utils.translation import ugettext_lazy as _ 

class InlineTypeManager(models.Manager): 
    def get_by_natural_key(self, title, app_label, model): 
        return self.get(title=title, content_type=ContentType.objects.get_by_natural_key(app_label=content_type__name, model=content_type__id)) 

class InlineType(models.Model): 
    title = models.CharField(_("title"), max_length=255) 
    content_type = models.ForeignKey(ContentType, limit_choices_to={"model__in": ("Link", "Document", "Image", "Audio", "Video", "MediaSet", "Flash", "Testimonial")}) 

    objects = InlineTypeManager() 

    class Meta: 
        ordering  = ["title"] 
        verbose_name = _("inline type") 
        verbose_name_plural = _("inline types") 

    def __unicode__(self): 
        return u"%s" % (self.title) 

https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys

我的initial_data.json

[
    {
        "model": "inlines.inlinetype",
        "pk": 1,
        "fields": {
            "title": "Image",
            "content_type": "image"
        }
    }, {
        "model": "inlines.inlinetype",
        "pk": 2,
        "fields": {
            "title": "Video",
            "content_type": "video"
        }
    }
]

當我loaddata JSON數據時,收到錯誤消息:

DeserializationError: [u"'image' value must be an integer."] 

get_by_natural_key是要在“人類友好的”查找中加載非整數字段,因為JSON中的硬編碼ID由於其不可預測性是一個壞主意,所以我猜我的經理失敗了。 還是應該使用get_for_model() / get_for_models()

Django中的自然鍵是

外鍵和多對多關系的默認序列化策略是序列化關系中對象的主鍵的值。

對於那些在轉儲目標中不會作為ForeignKey / ManyToManyField出現的模型,您不需要在Manager中實現諸如natural_key和get_by_natural_key之類的方法。 因此,您可以刪除InlineTypeManager()行。

另外,轉儲的initial_data.json中content_type字段的值不正確。 Django僅將列表視為自然鍵,像“ image”這樣的字符串仍被視為代理鍵,並且由於無法成功強制轉換為int而失敗。 正確的ContentType轉儲看起來像

from django.contrib.contenttypes.models import ContentType
from django.utils import simplejson

>>> simplejson.dumps(ContentType.objects.get(model='user').natural_key())
'["auth", "user"]'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM