Difference between question_id and question.id in DJANGO (Python)

Viewed 111

I am a complete Django beginner . I am finding some difficulties in understanding the concepts of using (.set and _set) methods, (.id and _ id ) methods and various methods like that. Currently i am referring Django Docs ->> https://docs.djangoproject.com/en/3.0/intro/ somebody help me in understanding these concepts ,like what is the reason behind the methods and where to use what king of method. Thank you.

1 Answers

Let's take an example, here are my 2 tables:

Owner(first_name, last_name)

Car(color, model, owner_id)

As you can see with a foreignkey relationship, django add a field owner_id in your table Car, where it will put the id of the owner of this car.

Now in your code, if you get a Car object it will contain this:

color <-- the color of the car

model <-- the model of the car

owner_id <-- the value of the field owner_id

owner <-- an object Owner

You can use car.owner_id (which is just an integer) or car.owner.id (Which go to find the id in the object owner.

What is the difference: Django is lazy, which means that it will not get the object owner if you don't use it. That means that if at no moment in your code you do a car.owner.whateveryouwant, there will be no object owner in your object car. And it avoid Django to get it from the database

When do we use one or the other: If you don't use the object owner from the object car and you just need the id, use car.owner_id, like that you'll not have to pull the owner object from the database.

If you use this object owner, there is no difference, you can use car.owner_id or car.owner.id anyway Django will have to get the owner object because you use it.

Related