django:如何将字段的父属性用于字段的默认值

时间:2015-04-08 18:23:54

标签: python django model

我想将默认类别设置为父类别设置的任何类别。

这是现在的基本对象模型:

class Product(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, related_name="variants")
    category = models.ForeignKey(Category, related_name='products')

我希望能够做到这样的事情:

    category = models.ForeignKey(Category, related_name='products', default=get_parent_category)

但我不知道如何获得父类的类别(该方法会是什么样子?)。有没有更好的方法呢?

(问题与this one相关)

1 个答案:

答案 0 :(得分:2)

覆盖保存方法。

class Product(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True,related_name="variants")
    category = models.ForeignKey(Category, related_name='products')

def save(self, *args, **kwargs):
    if self.parent and not self.pk and not self.category:
        self.category = self.parent.category  # Could use setattr getattr too but this is easier to read imo
    return super(Product, self).save(*args, **kwargs)

如果不使用self.pk,那么只有在将模型提交到数据库之前才会发生这种情况。