DJANGO在字段中将模型类型保存为通用外键

时间:2018-08-22 10:53:32

标签: python django

嘿,我想创建一个看起来像这样的新模型:

class Note(models.Model):
   id = models.AutoField(primary_key=True)
   title = ...
   message = 
   entity = *****************

我希望*******是任何模型的先键-不是对象而是模型。我不希望实体是同一模型的多个对象,而只是模型。

因此,如果注释来自Post实体,则应另存为Post,如果注释来自Notification,则foriengKey应该为Notification。

有没有办法在django中做到这一点?还是我唯一的选择,就是将实体名称保存为字符串值?并过滤模型名称,例如。

# Get all the notes for POST Model
Note.objects.filter(entity="Post")

2 个答案:

答案 0 :(得分:1)

您可以在Django中使用contenttypes应用。

class Note(models.Model):
   id = models.AutoField(primary_key=True)
   title = models.CharField(max_length=50)
   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
   object_id = models.PositiveIntegerField()
   entity = GenericForeignKey('content_type', 'object_id')

您将能够分配entity模型实例,并对其执行查询(filter(entity=MyModel.objects.get(id=1))

答案 1 :(得分:1)

听起来您真正想要的是'choices'。

  

由以下组成的可迭代对象组成的可迭代对象(例如列表或元组)   恰好有两个项目(例如[(A,B),(A,B)...])可用作选择   这个领域。如果指定了此选项,则默认的表单小部件将是一个选择   带有这些选项的框,而不是标准文本字段。

现在您的模型变为

class Note(models.Model):
    POST = "Post"
    COMMENT = "Comment"
    ...
    ENTITY_CHOICES( (POST,POST), (Comment, Comment) ...)

    id = models.AutoField(primary_key=True)
    title = ...
    message = ...
    entity = models.CharField(max_lenth=5, choices=ENTITY_CHOICES)

现在您可以在评论中运行查询

 Note.objects.filter(entity="Post")