外键对象在django rest中不可迭代

时间:2016-07-18 16:51:42

标签: django-rest-framework

当我尝试在api root中使用外键访问模型时,出现迭代错误。我找不到类似的案例来推荐。有人可以为我提供解决方案吗?

My error is:

    TypeError at /products/
    'Store' object is not iterable
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/products/
    Django Version: 1.7.3
    Exception Type: TypeError
    Exception Value:    
    'Store' object is not iterable
    Exception Location: /Library/Python/2.7/site-packages/rest_framework/relations.py in to_representation, line 488
    Python Executable:  /usr/bin/python
    Python Version: 2.7.6
    Python Path:    
    ['/Users/guanqiaowang/Desktop/Django/Django_venv/localdis',
     '/Library/Python/2.7/site-packages/distribute-0.6.28-py2.7.egg',
     '/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-intel.egg',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
     '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',

在models.py

from django.db import models
from django.utils import timezone
from datetime import datetime

# Create your models here.

class Store(models.Model):

  store_name = models.CharField(max_length=200)
  street = models.CharField(max_length=100)
  district = models.CharField(max_length=100)
  city = models.CharField(max_length=100)
  province = models.CharField(max_length=100)
  longtitude = models.DecimalField(max_digits=999,decimal_places=6)
  latitiude = models.DecimalField(max_digits=999,decimal_places=6)
  created = models.DateTimeField(default= datetime.now, blank=True)

  def __str__(self):
    return self.store_name

  # order by created time
  class Meta:
    ordering = ('created',)

class Product(models.Model):

  product_name = models.CharField(max_length=100)
  product_image =  models.CharField(max_length=100)
  category = models.CharField(max_length=100,blank = True)
  published_time = models.DateTimeField(default = datetime.now,blank = False,null=False)
  store_id = models.ForeignKey(Store,default=1,related_name='store_id')   # store_id to reference with stores
  # store_id = models = models.IntegerField()

  def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

  def __str__(self):
    return self.product_name

在serializers.py

from rest_framework import serializers
from mydis.models import Store,Product
class StoreSerializer(serializers.ModelSerializer):
    pk = serializers.ReadOnlyField()
    class Meta:
        model = Store
        fields = ('pk','store_name','street','district','city','province','longtitude','latitiude','created')
class ProductSerializer(serializers.ModelSerializer):
    store_id = serializers.PrimaryKeyRelatedField(many=True,queryset=Store.objects.all())
    class Meta:
        model = Product
        fields = ('product_name','product_image','category','published_time','store_id')

在views.py

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from mydis.serializers import StoreSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from mydis.models import Store,Product
from mydis.serializers import StoreSerializer,ProductSerializer
from rest_framework import viewsets

# Create your views here
class StoreViewSet(viewsets.ModelViewSet):
    serializer_class = StoreSerializer
    queryset = Store.objects.all()

class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    queryset = Product.objects.all()    

在urls.py

from mydis.views import StoreViewSet,ProductViewSet
from rest_framework.routers import DefaultRouter
from django.conf.urls import url,include
from mydis import views



router = DefaultRouter()
router.register(r'stores', StoreViewSet,base_name="Store")
router.register(r'products', ProductViewSet,base_name="Product")
# urlpatterns = router.urls

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

0 个答案:

没有答案