0

I'm reading the tutorial here, for Django 1.6: https://docs.djangoproject.com/en/1.6/intro/tutorial01/

and it uses the attribute choice_set, which I don't recognize. I thought this was the decapitalized child object (which was formed using ForeignKey as described earlier in the tutorial), but this yields an error when I try this myself. Is my assumption correct?

I know I'm not being the most concise, so just ask if you need further clarification.

Here is my models.py:

from django.contrib.auth.models import User

class Information(models.Model):
    title = models.CharField(max_length = 200)
    body = models.TextField()
    date = models.DateTimeField()

    def __unicode__(self):
        return self.title

class InformationChild(models.Model):
    information = models.ForeignKey(Information)
    child_text = models.CharField(max_length = 200)

    def __unicode__(self):
        return self.child_text

This is what I attempted:

i1 = Information.objects.filter(pk=1)
i1.informationchild_set.all()

This should return an empty list according to the tutorial, as I haven't set any children to the parent. If I'm understanding this correctly at all, that is.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
KSHMR
  • 741
  • 1
  • 9
  • 24
  • Show us your code so that we can be sure that the error you are seeing is the error you should see, rather than something you did wrong. – wheaties Jun 05 '14 at 14:47
  • Ok code is up in original post. – KSHMR Jun 05 '14 at 14:51
  • 2
    You need to change `Information.objects.filter(pk=1)` for `Information.objects.get(pk=1)`. `filter` returns a queryset whereas `get` returns the object itself – César Jun 05 '14 at 14:53
  • Aha, thank you! Works like a charm. Can you explain to me what a queryset is? The docs are not very explicit. – KSHMR Jun 05 '14 at 14:56

1 Answers1

1

The filter method returns a QuerySet and not one model instance. A QuerySet is a Django object that represents a query to the database, that can be filtered, sliced and iterated to get results. You could get the first result of the QuerySet with i1[0] but it is not the best way for you.

In you case, since you are sure to get one and only one result to your query, you need to use the get method:

i1 = Information.objects.get(pk=1)

# then, this is possible:
i1.informationchild_set.all()

See also: Difference between Django's filter() and get() methods

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97