我想查找特定用户创建articles
条记录的articlehistory
个数。
这个模型看起来像这样:
class Article(models.Model):
"""The basic entity of this app.)"""
documentID = models.CharField(blank=True, max_length=1000)
cowcode = models.IntegerField(blank=True, null=True)
pubdate = models.DateField(default=datetime.datetime.today)
headline = models.CharField(blank=True, max_length=1500)
source = models.CharField(blank=True, max_length=5000)
text = models.TextField(blank=True, max_length=1000000)
assignments = models.ManyToManyField(Assignment)
class Meta:
ordering = ['pubdate']
def __unicode__(self):
return self.headline
class ArticleHistory(models.Model):
"""(Modelname description)"""
article = models.ForeignKey(Article, related_name='Article History')
coder = models.ForeignKey(User, related_name='Article History')
last_updated = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return self.last_updated
我现在试图这样做的方式是这样的:
assignment.finished_articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date), articlehistory__coder=request.user.id).count()
然而,这不起作用,并表现出另一种奇怪的行为:
我试着这样做:
for assignment in assignments:
country = assignment.country.cowcode
start_date = assignment.start_date
end_date = assignment.end_date
articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date)).select_related()
assignment.article_num = articles.count()
#assignment.finished_articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date), articlehistory__coder=request.user.id).count()
这很好,除非我尝试包含finished_articles
,然后article_num
缩短为一个结果。
如果有人指向谁来解决这个问题,那真的很棒。
答案 0 :(得分:0)
利用参数related_name:
创建的ForeignKey的反向关系"article_history_set"
。user.article_history_set
是一组文章历史记录对象,其中编码器设置为此用户。article_history.article
找到与之相关的文章。您可以在此处了解有关related_name属性的更多信息:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name