Django Database querying differences -


i going through creation of polls app again, in django docs. wanted ask again 1 particular thing in django database. code shown below:

>>> polls.models import poll, choice  # make sure our __unicode__() addition worked. >>> poll.objects.all() [<poll: what's up?>]  # django provides rich database lookup api that's entirely driven # keyword arguments. >>> poll.objects.filter(id=1) [<poll: what's up?>] >>> poll.objects.filter(question__startswith='what') [<poll: what's up?>]  # poll published year. >>> django.utils import timezone >>> current_year = timezone.now().year >>> poll.objects.get(pub_date__year=current_year) <poll: what's up?>  # request id doesn't exist, raise exception. >>> poll.objects.get(id=2) traceback (most recent call last):     ... doesnotexist: poll matching query not exist. lookup parameters {'id': 2}  # lookup primary key common case, django provides # shortcut primary-key exact lookups. # following identical poll.objects.get(id=1). >>> poll.objects.get(pk=1) <poll: what's up?>  # make sure our custom method worked. >>> p = poll.objects.get(pk=1) >>> p.was_published_recently() true  # give poll couple of choices. create call constructs new # choice object, insert statement, adds choice set # of available choices , returns new choice object. django creates # set hold "other side" of foreignkey relation # (e.g. poll's choices) can accessed via api. >>> p = poll.objects.get(pk=1)  # display choices related object set -- none far. >>> p.choice_set.all() []  # create 3 choices. >>> p.choice_set.create(choice_text='not much', votes=0) <choice: not much> >>> p.choice_set.create(choice_text='the sky', votes=0) <choice: sky> >>> c = p.choice_set.create(choice_text='just hacking again', votes=0)  # choice objects have api access related poll objects. >>> c.poll <poll: what's up?> 

if take @ variable c, see created using this, p.choice_set.create(choice_text='just hacking again', votes=0). if created instead this: c = p.choice_set.filter(id=3), , when type in c.poll, give error. why happen? console gives me error : attributeerror: 'poll' object has no attribute 'create', not understand means.

also, there way of getting c.poll give output without having create new choice?

-- in advance

c = p.choice_set.filter(id=3) won't return single choice object. returns queryset composed of single choice object because, obviously, there 1 object same id. querysets iterables, means if want obtain choice object variable should be: c = p.choice_set.filter(id=3)[0] difference choice_set.create: create returns single created object.

now, that's not way it. when know querying single object, use get. c = p.choice_set.get(id=3).

see querying documentation further details.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -