从ManyToMany查询集序列化数据

时间:2013-11-30 19:52:15

标签: 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 manage.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'

1 个答案:

答案 0 :(得分:2)

问题源于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 managers.py并更改此行(在TaggableManager初始化函数内):

    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)
    
  3. 这是一种黑客攻击,但也许对你来说已经足够了。对不起,我不能再帮忙了!