简体   繁体   English

如何在Django中的ContentType外键上使用get_by_natural_key()加载数据夹具?

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

I'm having trouble loading an external data fixture for a model that uses a ContentType foreign key. 我在为使用ContentType外键的模型加载外部数据夹具时遇到问题。

I'm using a manager in the models, like the docs say. 我在模型中使用经理,就像文档所说的那样。 Unfortunately, although the docs talk about the importance of a get_by_natural_key method on a ContentType foreign key, it then launches into a different example instead. 不幸的是,尽管文档讨论了ContentType外键上的get_by_natural_key方法的重要性,但随后它启动了另一个示例。 I'm having trouble figuring out just what the manager would look like. 我很难弄清经理的模样。 My best guess is to use get_by_natural_key again, and assign app_label and model lookups, but I could be way off. 我最好的猜测是再次使用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 https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys

My initial_data.json : 我的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"
        }
    }
]

When I loaddata my JSON, I receive the error: 当我loaddata JSON数据时,收到错误消息:

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

The point of get_by_natural_key is to load non-integer fields in a "human-friendly" lookup because hard-coded IDs in the JSON is a bad idea because of its unpredictability, so I'm guessing my manager is failing. get_by_natural_key是要在“人类友好的”查找中加载非整数字段,因为JSON中的硬编码ID由于其不可预测性是一个坏主意,所以我猜我的经理失败了。 Or should I use get_for_model() / get_for_models() ? 还是应该使用get_for_model() / get_for_models()

natural key in Django is Django中的自然键是

The default serialization strategy for foreign keys and many-to-many relations is to serialize the value of the primary key(s) of the objects in the relation. 外键和多对多关系的默认序列化策略是序列化关系中对象的主键的值。

You don't need to implement methods such as natural_key and get_by_natural_key in Manager for those models which do not occur as ForeignKey/ManyToManyField in targets to dump. 对于那些在转储目标中不会作为ForeignKey / ManyToManyField出现的模型,您不需要在Manager中实现诸如natural_key和get_by_natural_key之类的方法。 So you could remove InlineTypeManager() lines. 因此,您可以删除InlineTypeManager()行。

Also, the values of content_type field inside dumped initial_data.json are incorrect. 另外,转储的initial_data.json中content_type字段的值不正确。 Django only treats a list as natural key, a string like "image" is still treated as surrogate key and will fail because it cannot be coerced to int successfully. Django仅将列表视为自然键,像“ image”这样的字符串仍被视为代理键,并且由于无法成功强制转换为int而失败。 Correct ContentType dump looks like 正确的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.

相关问题 Django-get_by_natural_key()恰好接受3个参数(给定2个) - Django - get_by_natural_key() takes exactly 3 arguments (2 given) get_by_natural_key 和 natural_key 的区别 - Difference between get_by_natural_key and natural_key 创建超级用户时出现Django错误,AttributeError:'Manager'对象没有属性'get_by_natural_key' - Django error while creating superuser, AttributeError: 'Manager' object has no attribute 'get_by_natural_key' AttributeError: 'Manager' object has no attribute 'get_by_natural_key' 错误在Django? - AttributeError: 'Manager' object has no attribute 'get_by_natural_key' error in Django? 使用自然键导入 django 夹具时出错 - Error when importing django fixture with natural key 在 _validate_username AttributeError: 'Manager' object has no attribute 'get_by_natural_key' 错误 - in _validate_username AttributeError: 'Manager' object has no attribute 'get_by_natural_key' error 在 django 中,如何获取具有精确外键的所有数据? 例如,获取外键 = 1 或 2 的所有帖子或 - In django, how to get all data with exact foreign key? example, get all posts with foreign key = 1 or 2 or django查询语句中如何通过外键和自然键显示不同表的字段 - How to show fields from different table through foreign key and natural key in django query statement Django:如何从外键和下一个外键中获取值? - Django: How to get value from foreign key and next foreign key? 如何从 django 中的外键获取数据 - How can get the data from the foreign key in django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM