相关领域的模型序列化器TypeError

时间:2017-07-03 15:41:06

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

之前我从未使用过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

1 个答案:

答案 0 :(得分:0)

必须在视图中向序列化程序添加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)