在Django 2.0中挣扎于属性

时间:2018-05-01 08:26:12

标签: python django for-loop django-models

这是我的代码:

class Product(models.Model) :
    name = models.CharField(max_length=150)
    price = models.DecimalField(max_digits=15, decimal_places=10)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
    date = models.DateField(auto_now=True, auto_now_add=False)
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE, blank=True, null=True)
    slug = models.SlugField(max_length=100)
    is_featured = models.BooleanField(default=False)
    descripition = models.TextField()
    is_published = models.BooleanField(default=True)
    attributes = models.ManyToManyField('Attribute')

    def __str__(self) :
        return self.name

    class Meta :
        ordering = ("-date",)

class ProductVariant(models.Model) :
    sku = models.CharField(max_length=120, unique=True)
    name = models.CharField(max_length=120, blank=False, null=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

    for attri in product.attributes :
        attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name})

    class Meta :
        ordering = ("name",)

    def __str__(self) :
        return self.product.name + self.name

class Attribute(models.Model) :
    name = models.CharField(max_length=120)

    def __str__(self) :
        return self.name

    class Meta :
        ordering = ("name",)

class AttributeVariant(models.Model) :
    name = models.CharField(max_length=120)
    attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, related_name='values')

    class Meta :
        ordering = ("name",)

    def __str__(self) :
        return self.name

我想做的事情:

在ProductVariant类中,我尝试通过产品属性,并为每个属性分配一个字段ForeignKey到AttributeVariants以获取此特定属性的值。它对应于以下代码:

for attri in product.attributes :
    attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name})

然而,当我尝试运行 python manage.py makemigrations 时,我得到了

    for attri in product.attributes :
        AttributeError: 'ForeignKey' object has no attribute 'attributes'

如果您找到解决此问题的方法,请与我们联系。 谢谢!

0 个答案:

没有答案