Mah*_*sam 4 python django django-models
假设我有一个Issue
看起来像这样的模型:
class Issue(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
text = models.TextField()
Run Code Online (Sandbox Code Playgroud)
还有一个叫做Comment
:
class Comment(models.Model):
issue = models.ForeignKey(Issue)
text = models.TextField()
number = models.AutoField()
Run Code Online (Sandbox Code Playgroud)
我希望评论编号字段与问题相关.
这意味着每个问题都会有单独的评论#1,评论#2,评论#3 ......等.
这可以在Django中完成吗?
如果您从评论模型中删除了数字字段并将其替换为date_added字段,您仍然可以查询数据库以按顺序提取与特定条目关联的所有评论.
class Comment(models.Model):
issue = models.ForeignKey(Issue)
text = models.TextField()
date_added = models.DateField(auto_add_now = True)
Run Code Online (Sandbox Code Playgroud)
然后,如果您想获得与某个问题相关的所有评论:
i = Issue.object.get(pk=1) #pk = primary key id for whatever issue you want
comments_by_issue = i.comment_set.all().order_by('date_added')
Run Code Online (Sandbox Code Playgroud)
现在您有一些注释可以通过索引位置引用(例如,comments_by_issue [0]可以获得附加到该问题的第一条注释).
索引位置是我能想到的最接近你想要的东西.有人提到了comment.id,但这只是一个自动递增的整数,每个评论都会有所增加.添加到您的系统的第五个注释可能有comment.id = 5,但它可能是第2个附加的第一条注释 - 如果我正确地阅读您的查询,那么注释ID在该上下文中没有帮助.
这是一个解决方法而不是直接的答案,但我希望它有所帮助.
归档时间: |
|
查看次数: |
849 次 |
最近记录: |