【发布时间】:2021-08-09 14:50:43
【问题描述】:
我在尝试在 Django 模型中定义属性并访问它们时遇到了问题。我有 2 个模型,第一个是产品,第二个是产品属性。产品属性有几个字段,如颜色和品牌。我想创建属性来获取产品的品牌和颜色,以便在模板和过滤(django-filter)中使用,但模型中的属性没有按预期给出结果。请找到以下代码和备注供您参考和帮助。
产品型号:
class Product(models.Model):
measurement_choices = (('Liter', 'Liter'), ('Kilogram', 'Kilogram'), ('Cloth', 'Cloth'), ('Shoe', 'Shoe'))
name = models.CharField(max_length=200)
sku = models.CharField(max_length=30, null=True)
stock = models.CharField(max_length=10, null=True)
measurement = models.CharField(choices=measurement_choices, max_length=20, null=True)
description = models.CharField(max_length=10000)
price = models.DecimalField(max_digits=7, decimal_places=2)
discounted_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True)
image_one = models.ImageField(upload_to='product/images', null=True, blank=True)
image_two = models.ImageField(upload_to='product/images', null=True, blank=True)
image_three = models.ImageField(upload_to='product/images', null=True, blank=True)
image_four = models.ImageField(upload_to='product/images', null=True, blank=True)
image_five = models.ImageField(upload_to='product/images', null=True, blank=True)
tags = models.ManyToManyField(Tags)
sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL,
null=True,related_name='+')
status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive',
'Inactive')))
history = HistoricalRecords()
我为获得品牌名称而创建的属性:
def p_brand(self):
brand = ''
all_attributes = self.productattribute_set.all()
for att in all_attributes:
brand = att.brand.title
print(brand)
return brand
此属性在视图中返回以下结果,而不是品牌名称:
<bound method Product.p_brand of <Product: 1:T-Shirt:Men>>
<bound method Product.p_brand of <Product: 2:Shoe:Men>>
<bound method Product.p_brand of <Product: 3:Book:Men>>
产品属性模型:
class ProductAttribute(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True,
blank=True)
color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True,
blank=True)
size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True, blank=True)
price = models.PositiveIntegerField(default=0)
offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True,
blank=True)
image = models.ImageField(upload_to="product_imgs/", null=True, blank=True)
history = HistoricalRecords()
我也尝试过使用下面的方法来获得品牌,效果很好。
for product in Product.objects.all():
attr = product.productattribute_set.all()
for att in attr:
print(att.brand.title)
【问题讨论】:
标签: python-3.x django django-models django-views