Django外键和一对多的关系

时间:2018-01-23 17:04:07

标签: django

我试图建立一个基本的电子商务网站,作为学习django的意思。我正在尝试构建我的模型,因此有一个Category,一个Product和Product Image类来存储我的数据。这是我的models.py:

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)

    class Meta:
        ordering = ('name', )
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('products:product_list_by_category', args=[self.slug])


class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField()
    available = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name', )
        index_together = (('id', 'slug'), )

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('products:product_detail', args=[self.id, self.slug])


class ProductImage(models.Model):
    property = models.ForeignKey('Product', related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products')

这是我的views.py:

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)

    product_img = Product.images.all()

    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)

    return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products, 'product_img': product_img})

我在堆栈溢出时看到类似的帖子,并试图做同样的事情,但我仍然收到以下错误:AttributeError:' ReverseManyToOneDescriptor'对象没有属性' all'

我在哪里错了?

0 个答案:

没有答案