gpt4 book ai didi

Django:检查是否设置了外键属性

转载 作者:行者123 更新时间:2023-12-04 02:41:32 29 4
gpt4 key购买 nike

我有以下模型:

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

这个模型应该是一些继承树中的根模型,而 content_type 属性是一种关于真正存储什么类型的提示。
显然,我应该计算 content_type在 A 实例创建时透明。我认为,在 __init__ .但是有一个问题——创建 A 实例有两个主要上下文:
  • a = A(name='asdfdf') # here we must fill in content_type
  • 来自 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属性设置?

    最佳答案

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

    关于Django:检查是否设置了外键属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005161/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com