【问题标题】:Model Serializer TypeError on Related Field相关字段上的模型序列化器 TypeError
【发布时间】:2017-07-03 15:41:05
【问题描述】:

我以前从未使用过 Django Rest Framework,但我想序列化我的一些模型,因为我想最终通过 JS 而不是 Django 获取和发布这些特定模型的信息。我有一个工作正常,但一个名为 ManifestSerializer 的程序给了我错误:TypeError: 'Freight' object is not iterable。这是我的代码:

Models.py:

class Freight(models.Model):
    pu_location = models.OneToOneField(AddressBook, to_field='address', related_name='pu_location')
    pu_customer = models.CharField(max_length=200)
    pu_appt_time = models.DateTimeField(default=datetime.now)
    po_number = models.CharField(max_length=20)
    load_number = models.CharField(max_length=10, blank=True, null=True)
    pallet_count = models.IntegerField(validators=[MaxValueValidator(99)])
    content_type = models.CharField(max_length=20, choices=[('Frozen', 'Frozen'), ('Chilled', 'Chilled'), ('Dry', 'Dry')])
    cases_count = models.IntegerField(validators=[MaxValueValidator(9999)])
    weight = models.IntegerField(validators=[MaxValueValidator(99999)])
    del_customer = models.CharField(max_length=200)
    del_location = models.OneToOneField(AddressBook, to_field='address', related_name='del_location')
    del_city = models.CharField(max_length=50, blank=True, null=True)
    del_state = models.CharField(max_length=2, blank=True, null=True)
    del_appt_time = models.DateTimeField(default=datetime.now)
    invoice_amount = models.DecimalField(max_digits=8, decimal_places=2)
    status = models.CharField(max_length=20, choices=[('New', 'New'), ('EnRoute', 'En Route'), ('Complete', 'Complete'), ('NotExecuted', 'Not Executed')], default='New')
    note = models.ForeignKey(Note, blank=True, null=True)

    def save(self, *args, **kwargs):
        reg = re.compile(r',\s+?(?P<city>[^,]+),\s+(?P<state>[A-Za-z]{2})')
        location = str(self.del_location)
        extract = reg.search(location)
        city = extract.group('city')
        state = extract.group('state')

        if not self.del_city:
            self.del_city = city
        if not self.del_state:
            self.del_state = state
        super(Freight, self).save(*args, **kwargs)

    def __unicode__(self):
        return "%s : %s : %s" % (self.po_number, self.pu_customer, self.del_location)


class Manifest(models.Model):
    manifest_number = models.AutoField(primary_key=True)
    freight = models.ForeignKey(Freight)
    status = models.CharField(max_length=20, choices=[('New', 'New'), ('Pending', 'Pending'), ('InProgress', 'In Progress'), ('Complete', 'Complete')], default='New')
    note = models.ForeignKey(Note, blank=True, null=True)
    weight = models.IntegerField(validators=[MaxValueValidator(99999)])
    pallet_count = models.IntegerField(validators=[MaxValueValidator(99)])
    revenue = models.DecimalField(max_digits=10, decimal_places=2)
    trailer = models.ForeignKey(Trailer)
    created_on = models.DateTimeField(default=datetime.now)
    status_change = models.DateTimeField(blank=True, null=True)

    def __unicode__(self):
        return "%d" % self.manifest_number

Serializers.py:

from rest_framework import serializers
from dispatch.models import Manifest, Freight


class FreightSerializer(serializers.ModelSerializer):

    class Meta:
        model = Freight
        fields = '__all__'


class ManifestSerializer(serializers.ModelSerializer):

    class Meta:
        model = Manifest
        fields = '__all__'

追溯:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/rest_framework/serializers.py", line 534, in data
    ret = super(Serializer, self).data
  File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/rest_framework/serializers.py", line 263, in data
    self._data = self.to_representation(self.instance)
  File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/rest_framework/serializers.py", line 501, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/home/jboucher/anaconda3/envs/openroad/lib/python3.6/site-packages/rest_framework/relations.py", line 515, in to_representation
    for value in iterable
TypeError: 'Freight' object is not iterable

【问题讨论】:

  • 你能发布视图的代码吗?
  • 感谢您的回复。当你的评论进来时,我终于修好了。

标签: django django-rest-framework django-serializer


【解决方案1】:

必须将 many=true 添加到视图中的序列化程序以获取信息。这是当前视图:

Views.py:

@api_view()
def freight_list(request):

    freight = Freight.objects.all()
    serializer = FreightSerializer(freight, many=True)
    return Response(serializer.data)


@api_view()
def manifest_list(request):

    manifest = Manifest.objects.all()
    serializer = ManifestSerializer(manifest, many=True)
    return Response(serializer.data)

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2023-03-25
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2021-03-13
    • 2020-06-29
    • 2014-01-05
    • 1970-01-01
    相关资源
    最近更新 更多