我想创建一个如下所示的新模型:
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/