david yeritsyan
david yeritsyan

Reputation: 452

django tutorial poll app, trying to understand logic

I'm trying to understand the logic of linking foreign keys to primary keys, so far everything seems pretty straight forward except this one part which is throwing me off, if anyone can clarify that I would really appreciate it

So this first portion I would be linking the row with primary key 1 to the variable q

>>> q = Question.objects.get(pk=1)


>>> q.choice_set.all()
<QuerySet []>

Basically Creating choices and linking them to q (which consists of the question associated to primary key 1)

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>

This is the part thats throwing me OFF! Why do I have to all of a sudden on the last choice set it the variable c?

>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects.

I see that the question is set inside of variable c, but what was the point, is there a specific reason that the last choice had to be set to a new variable c??

Is this conventional? and what i'm trying to ask is.. Everytime I create some type of foreign key relationship does my child entity (in this case choice) be linked to a new variable at the end (c in this case), and what is the significance of that?

>>> c.question
<Question: What's up?>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()

I tried looking through the documentation on the reasoning and can't find anything

Upvotes: 1

Views: 261

Answers (1)

Carl Brubaker
Carl Brubaker

Reputation: 1655

When you create an object, you do not have to assign it a variable. It is just convenient if you intend on using the created object.

object = Model.objects.create(parameters)

And

Model.objects.create(parameters)
object = Model.objects.get(parameters)

Are the same. ForeignKey is just another parameter (or field) stored when the object is created.

A ForeignKey field stores a reference to an object in another Model. When they call c.question, it returns the question object referenced in the choice's ForeignKey field. The __str__ method of the Question object is the text that you see.

Upvotes: 1

Related Questions