Filtering on foreign key relationship - Django -
i want find number of articles
specific user has created articlehistory
records.
models this:
class article(models.model): """the basic entity of 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
the way i'm trying @ moment this:
assignment.finished_articles = article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date), articlehistory__coder=request.user.id).count()
this doesn't work, , exhibits weird behaviour:
try this:
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()
this works fine, unless try include finished_articles
, article_num
gets shortened 1 result.
it great if has pointer solve this.
make use of reverse relation of foreignkey created parameter related_name:
- rename attribute related name
"article_history_set"
. - now, gives easy pointer:
user.article_history_set
set of article history objects coder set user. - then can find article related doing
article_history.article
. - at end, have rid of repetition , length of list.
here have more related_name attribute: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.foreignkey.related_name
Comments
Post a Comment