0
我想找到articles
的數量,其中特定用戶創建了articlehistory
記錄。
的看起來像這樣的模式:在外鍵關係上過濾 - Django
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
縮短爲一個結果。
如果有人指出誰來解決這個問題,這將是非常好的。
謝謝!你的意思是改變'coder = models.ForeignKey(User,related_name ='文章歷史')''coder = models.ForeignKey(User,related_name ='article_history_set')',對嗎? – LukasKawerau
其實,'related_name =「whatever_you_want_but_without_spaces」'。該字符串將用作用戶屬性的名稱:'user.whatever_you_want_but_without_spaces'。所以,我不認爲這樣的名稱與空間會起作用;) – BUZZY