Django QuerysSet for finding related foreign key fields -
i'm trying query related field catalog class in many items related foreign key. i'm trying:
article = forms.modelchoicefield(queryset=catalog.objects.select_related( 'article_products'))
it seems same query as:
queryset = catalog.objects.all()
can help steer me in right direction? here model i'm working with.
class catalog(models.model): products = models.charfield(max_length=200) def __unicode__(self): homecoming self.products class article(models.model): catalog = models.foreignkey(catalog, related_name='article_products') title = models.charfield(max_length=200) abstract = models.textfield(max_length=1000, blank=true) full_text = models.textfield(blank=true) proquest_link = models.charfield(max_length=200, blank=true, null=true) ebsco_link = models.charfield(max_length=200, blank=true, null=true) def __unicode__(self): homecoming self.title
my goal have form select field of articles related catalog. displays name of catalog.
i not think select_related method accomplish goal have set out accomplish modelchoicefield. quite right 2 queries below homecoming same resulting queryset:
catalog.objects.all().select_related('article_products')) catalog.objects.all()
the select_related method of django querysets serves different function, performance booster cut down number of database accesses required obtain info want retrieve model instance. the django reference method contains documentation, examples explaining why utilize select_related method performance purposes.
with beingness said, original purpose remains: form field display of articles related given catalog.
in order accomplish goal, seems best filter queryset of article objects beingness given form field. first of all, if want display article objects within modelchoicefield, should give modelchoicefield queryset containing article objects rather catalog objects, so:
article = forms.modelchoicefield(queryset=article.objects.all())
but queryset argument not quite right, either. still passing queryset of article objects exist in database. instead, want pass articles associated given catalog object. accomplish goal, can filter article queryset obtain article objects related catalog object, so:
# cat catalog object article = forms.modelchoicefield(queryset=article.objects.filter(catalog=cat))
in example, queryset filter returns article objects contain reference given catalog object. queryset used populate modelchoicefield.
for more info filtering field lookup, see django documentation here.
django django-models django-forms
No comments:
Post a Comment