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

标签 django django-models

我有以下模型:

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/

    相关文章:

    python - 尝试使用 django.client 批量上传到 django-rest-framework (ModelViewSets)

    python - 在 Pycharm 中以 DEBUG 模式跳过 Django 服务器上的系统检查

    python - Django 无法导入名称 x

    Django:检查模板中多对多字段中的值

    使用 get_queryset 的 Django ListView 分页

    django - 仅在调用更新时发布保存信号

    django - Nginx:具有项目根的多个Django项目?

    Django-Filebrowser:获取 AttributeError: 'NoneType' 对象没有属性 'endswith'

    python - unique_together 不允许更新记录

    django - 在非主键关系上加入和查询 Django 模型?