【问题标题】:django: how to use a parent's attribute for a field's defaultdjango:如何使用父属性作为字段的默认值
【发布时间】:2015-04-08 18:23:54
【问题描述】:

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

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

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有关)

【问题讨论】:

  • 我会尝试在您的产品类上设置一个getter 方法,然后调用它

标签: python django model


【解决方案1】:

覆盖保存方法。

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,那么这只会在模型提交到数据库之前发生。

【讨论】:

  • 这是一个很好的解决方案。标记为已解决。 (为了完全正确,也许您可​​以将“if”语句下方的行编辑为 self.parent.category)。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
相关资源
最近更新 更多