Skip to main content
 首页 » 编程设计

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

2024年09月07日35Free-Thinker

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

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

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

因此,如果注释来自 Post 实体,则应保存为 Post,如果它来自 Notification,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")