类别对象不可迭代

时间:2015-11-10 13:59:47

标签: python django django-models django-views

我是django的初学者 我得到上述错误为“类别不可迭代”

提前致谢

models.py

这是我的类别模型

class Category(MPTTModel):
    title = models.CharField(max_length =120)
    parent = TreeForeignKey('self' , null = True , blank = True , verbose_name='parent category', related_name='categories')
    description = models.TextField(null=True , blank=True)
    active = models.BooleanField(default=True)
    slug = models.SlugField(unique=True)
    timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)

    def get_absolute_url(self):
            return reverse('categories', kwargs={'path': self.get_path()})

这是我的产品型号

class ProductManager(models.Manager):

    def get_queryset(self):
        return ProductQuerySet(self.model , using=self._db)

    def all(self,*args,**kwargs):
        return self.get_queryset().active() 

    def get_related(self, product):
        related_products = self.get_queryset().filter(category__in=product.category)
        qs = (related_products).exclude(id=product.id).distinct()
        return qs


class Product(models.Model):
    brand = TreeForeignKey('Brand', verbose_name='brand', related_name='products' , default='')
    category = TreeForeignKey('Category', verbose_name='Category', related_name='products' , default='')
    parent = models.ForeignKey('self' , related_name = 'children' , null=True , blank=True)
    title = models.CharField(max_length=120)
    SKU = models.CharField(max_length=100 , unique=True)
    description = models.TextField(max_length = 500 ,blank=True ,null=True)
    price = models.IntegerField()
    quantity = models.IntegerField(null=True , blank=True)
    discount = models.IntegerField(blank=True ,null =True)
    active = models.BooleanField(default=True)
    is_verified = models.BooleanField(default=False)
    in_stock = models.BooleanField(default=False)
    slug = models.SlugField(default='')

    objects = ProductManager()

    class Meta:
            unique_together = ('slug', 'category')


    def __unicode__(self):
        return self.title

这是views.py 随机导入

class ProductDetailView(DetailView):
    model = Product
    template_name = "products/product.html"
    #template_name = "<appname>/<modelname>_detail.html"
    def get_context_data(self, *args, **kwargs):
        context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
        product = self.get_object()
        #order_by("-title")
        context["related"] = sorted(Product.objects.get_related(product)[:6], key= lambda x: random.random())
        return context

它在这些行上给我错误

1 - context [“related”] = sorted(Product.objects.get_related(product)[:6],key = lambda x:random.random()) 和

2 - related_products = self.get_queryset()。filter(category__in = product.category)

0 个答案:

没有答案