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:

  1. rename attribute related name "article_history_set".
  2. now, gives easy pointer: user.article_history_set set of article history objects coder set user.
  3. then can find article related doing article_history.article.
  4. 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

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -