django - 从 ManyToMany 查询集中序列化数据

标签 django

class Food(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=199)
    tags = TaggableManager()

class Box(models.Model):
    user = models.ForeignKey(User)
    food = models.ManyToManyField(Food, blank=True, null=True)

python管理.py shell:

box = Box.objects.filter(id=1)
myfood = box.food.all()

我需要所有 myfood 的 JSON。我如何序列化这些数据?

我的尝试:

data = serializers.serialize("json", myfood)

但是我有这个错误:

    if field.rel.through._meta.auto_created:
AttributeError: 'NoneType' object has no attribute '_meta'

完整示例:(python manage.py shell):

>>> from django.core import serializers
>>> from app.models import *
>>> box = Box.objects.filter(id=1)
>>> myfood = box.food.all()
>>> data = serializers.serialize("json", myfood)

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/user/Pulpit/x/local/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 99, in serialize
    s.serialize(queryset, **options)
  File "/home/user/Pulpit/x/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 58, in serialize
    self.handle_m2m_field(obj, field)
  File "/home/user/Pulpit/x/local/lib/python2.7/site-packages/django/core/serializers/python.py", line 65, in handle_m2m_field
    if field.rel.through._meta.auto_created:
AttributeError: 'NoneType' object has no attribute '_meta'

最佳答案

问题源于 django 附带的序列化器,特别是处理 m2m 字段的函数:

def handle_m2m_field(self, obj, field):
    if field.rel.through._meta.auto_created:
        if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'):
            m2m_value = lambda value: value.natural_key()
        else:
            m2m_value = lambda value: smart_text(value._get_pk_val(), strings_only=True)
        self._current[field.name] = [m2m_value(related)
                           for related in getattr(obj, field.name).iterator()]

问题是,当它迭代对象的字段时,它还会找到 TaggableManager(它是一个管理器),并将其视为字段。然后,field.rel.through._meta.auto_created 行会导致错误(因为它不是字段)。我能想到两种可能的修复方法:

  1. 构建您自己的序列化器

  2. 申请this fix.打开 django-taggit manager.py 并更改此行(在 TaggableManager init 函数内):

    class TaggableManager(RelatedField, Field):
         def __init__(self, verbose_name=_("Tags"),
             help_text=_("A comma-separated list of tags."), through=None, blank=False):
             Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank)
    

    对此:

    class TaggableManager(RelatedField, Field):
         def __init__(self, verbose_name=_("Tags"),
             help_text=_("A comma-separated list of tags."), through=None, blank=False):
             Field.__init__(self, verbose_name=verbose_name, help_text=help_text, blank=blank, null=True, serialize=False)
    

这有点像黑客,但也许对你来说已经足够了。抱歉,我无法提供更多帮助!

关于django - 从 ManyToMany 查询集中序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304923/

相关文章:

python - 我无法在 python 中安装 mysqlclient 和 pillow

python - 处理 Django 模型和关系数据的正确/最有效的方法

python - 在 django 模板中格式化数字

Django:JSONField + 全文搜索 + 索引 -> 序列扫描。如何配置索引工作?

python - 如何在 Django 1.5 中反转自定义管理 url?

python - Django 更新该行(如果存在)

python - Django celery 导入错误 : no module named celery when using gunicorn bind?

Django REST Framework ManyToMany 过滤多个值

django - 使用 Django ORM 值并调用成员函数

python - Django 1.7.3 - 字段引用的模型查找失败