python - DJANGO 将字段中的模型类型保存为通用外键

标签 python django

我想创建一个如下所示的新模型:

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

我希望 ******** - 成为任何模型的 foreingKey - 不是对象而是模型。我不希望实体是同一模型的多个对象 - 只是模型。

因此,如果注释来自 Post 实体,则应保存为 Post;如果注释来自通知,则 foriengKey 应该保存为“Notification”。

有没有办法在 django 中执行此操作,或者我唯一的选择是将实体名称保存为字符串值?并过滤模型名称,例如。

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

最佳答案

听起来您真正要找的是“choices” '.

An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.

现在你的模型变成了

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")

关于python - DJANGO 将字段中的模型类型保存为通用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965277/

相关文章:

django - 使用staff_member_required装饰器,但没有重定向到管理界面?

python - Django - 如何过滤管理页面表中可编辑列中的外键选择?

python - 在Linux上部署Django项目

django - Docker-compose 添加 Postgres 密码

python - 创建保存列名和另一个数据框的相应值的 df

python - 理解 python 中的 csv DictWriter 语法

python - 基于唯一 ID 和范围截止值的分层 pandas 列

django - 如何在 Django 测试服务器中防止 HTTP 304

Python:使用列表理解通过子字符串列表过滤列表

python - 在函数中调用 patsy 时的命名空间问题