对象不是可迭代的Django

时间:2018-09-20 23:28:35

标签: django django-rest-framework

我已经将模型称为Order。当我尝试使用queryset初始化时出现问题。我得到的“订单”对象不是可迭代的,我认为get_queryset被调用两次的原因

views.py

class ChechoutViewSet(viewsets.ReadOnlyModelViewSet):

  serializer_class = serializers.OrderSerializer

  queryset = None  # this line is probably not required, but some code checking tools like it to be defined.

  def get_queryset(self):

      cart_obj, cart_created = Cart.objects.get_or_create(user_profile=self.request.user)
      billing_obj, billing_created = BillingProfile.objects.get_or_create(user_profile=self.request.user)

      if billing_obj is not None:
          self.queryset = models.Order.objects.new_or_get(billing_obj=billing_obj, cart_obj=cart_obj)

      return self.queryset

models.py

class OrderManager(models.Manager):

  def new_or_get(self, billing_obj, cart_obj):
    qs = Order.objects.filter(billing_profile=billing_obj, cart=cart_obj, active=True)

      if qs.exists():
        obj = qs
      else:
        obj = Order.objects.create(billing_profile=billing_obj, cart=cart_obj)

      return obj

2 个答案:

答案 0 :(得分:1)

obj = Order.objects.create(billing_profile=billing_obj, cart=cart_obj)行在db中创建该项目,然后在return obj行中将其返回。但是get_queryset应该返回一个查询集。我建议做以下事情:

if qs.exists():
    obj = qs
else:
    obj_created = Order.objects.create(billing_profile=billing_obj, cart=cart_obj)
    obj = Order.objects.filter(id=obj_created.id)

我建议确保返回值的类型符合预期。

答案 1 :(得分:1)

由于CheckoutViewSet.get_queryset方法,您的QuerySet方法并不总是返回OrderManager.new_or_get

OrderManager.new_or_get中,如果查询集不存在(if qs.exists()),则从对Order.objects.create的调用中返回单个对象,并且CheckoutViewSet.get_queryset也返回了该对象。

您可以修改CheckoutViewSet.get_queryset方法,以检查new_or_get的返回类型,并使用该方法返回查询集,下面提供了一个示例:

views.py

from django.db.models.query import QuerySet

class ChechoutViewSet(viewsets.ReadOnlyModelViewSet):

  serializer_class = serializers.OrderSerializer

  queryset = Order.objects.all()  # You should include this because it can be used to statically inspect the view

  def get_queryset(self):

      cart_obj, cart_created = Cart.objects.get_or_create(user_profile=self.request.user)
      billing_obj, billing_created = BillingProfile.objects.get_or_create(user_profile=self.request.user)

      ### Changes below
      if billing_obj is not None:
          order = models.Order.objects.new_or_get(billing_obj=billing_obj, cart_obj=cart_obj)
          if not isinstance(order, QuerySet):
             queryset = Order.objects.filter(pk=order.pk)
          else:
             queryset = order
          self.queryset = queryset

      return self.queryset

如果您的OrderManage.new_or_get方法未返回QuerySet,则假定它是Order的实例,并通过按对象的主键过滤该对象来返回QuerySet。这将导致QuerySet具有单个实例。