【问题标题】:Django: Check if foreign key attribute is setDjango:检查是否设置了外键属性
【发布时间】:2010-01-05 09:47:50
【问题描述】:

我有以下型号:

class A(models.Model):
    name = models.CharField(max_length=50)
    content_type = models.ForeignKey(ContentType)

这个模型应该是某个继承树中的根模型,而 content_type 属性是一种关于真正存储什么类型的提示。 显然,我应该在 A 实例创建时透明地计算content_type。我想,在__init__。但是有一个问题 - 创建 A 实例的主要上下文有两种:

  1. a = A(name='asdfdf') # here we must fill in content_type
  2. QuerySet 机器与*args 元组。在这种情况下我不应该填写content_type

所以,我正在尝试写:

def __init__(self, *args, **kwargs):
    super(A, self).__init__(*args, **kwargs)
    if self.content_type is None: # << here is the problem
        self.content_type = ContentType.objects.get_for_model(self)

事情是self.content_typeReverseSingleRelatedObjectDescriptor 实例,__get__ 被覆盖,以便在未设置值的情况下抛出。是的,我可以执行以下操作:

def __init__(self, *args, **kwargs):
    super(A, self).__init__(*args, **kwargs)
    try: 
        self.content_type
    except Exception, v:
        self.content_type = ContentType.objects.get_for_model(self)

但我不喜欢它。有没有更“礼貌”的方法来检查是否设置了ForeignKey 属性?

【问题讨论】:

  • 首先,如果您希望content_type 是可选的,我认为您需要在字段定义中设置blank = True, null = True
  • 我不希望它是可选的,我只是不想设置它的值,如果它已经被 Django 设置(在从 DB 读取的过程中)。

标签: django django-models


【解决方案1】:

如果您检查self.content_type_id 而不是self.content_type,它是否有效?

【讨论】:

  • 当然,你是对的。这正是我需要的。谢谢。
猜你喜欢
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 2015-10-27
  • 2011-11-03
  • 1970-01-01
相关资源
最近更新 更多