lfalanga
8/28/2015 - 11:25 AM

Get object by different criteria

# All objects
Poll.objects.all()

# By id
Poll.objects.filter(id=1)

# Field "question" starts with
Poll.objects.filter(question__startswith='What')

# DateField pub_date corresponds to this year
current_year = timezone.now().year
Poll.objects.get(pub_date__year=current_year)

# Using get instead of filter
Poll.objects.get(id=2)

# Getting object by primary key
Poll.objects.get(pk=1)

# Get all choices for p (RelatedManager)
p = Poll.objects.get(pk=1)
p.choice_set.all()

# Get Poll object for c
c = p.choice_set.create(choice='Just hacking again', votes=0)
c.poll