Django Tutorial – models, database, admin

Code / Syntax stuff from the tutorial that I’m definitely going to forget, so putting it here for easy reference:

Question.objects.all()
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith=’What’)

q = Question(question_text=”What’s new?”, pub_date=timezone.now())
q.save()

q.id
q.question_text
q.pub_date

is, utterly, an unhelpful representation of this object. Let’s fix that by editing the Question model (in the polls/models.py file) and adding a __str__() method to both Question and Choice:

t’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.

Question.objects.get(pub_date__year=current_year)

q = Question.objects.get(pk=1)
q.choice_set.all()

q.choice_set.count()

Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.create(choice_text=’Just hacking again’, votes=0)1

After logging in to Django admin, add the polls app to admin.py to make it modifiable in the admin section.

Pin It on Pinterest

Share This