SangminKim
SangminKim

Reputation: 9136

When django model access DB

i am curious how django model works.

it means when the model access DB.

for example we have this model Person, and the DB has record on first_name="abc"

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

and in order to access the data

per = Person.object.get(first_name="abc")   #does it have access to DB?   
first_name =  per.first_name                #otherwise it has access to DB?
first_name2 = per.first_name                #first_name is cached? or it has to access DB again?

Upvotes: 1

Views: 70

Answers (1)

lifeng.luck
lifeng.luck

Reputation: 601

I use a similar model to demonstrate it :

My model: class IC(models.Model):

    partno = models.CharField(max_length=200, unique=False)  # 型号名
    sups = models.CharField(max_length=500, blank=True, default=None)
    mfr = models.ForeignKey(Mfr)

and you can do like this, it will print all sql queries sent by Django.

>>> import logging
>>> logger = logging.getLogger('django.db.backends')
>>> logger.setLevel(logging.DEBUG)
>>> logger.addHandler(logging.StreamHandler())

>>> ic = IC.objects.get(id='21')
(0.001) SELECT `icbase_ic`.`id`, `icbase_ic`.`partno`, `icbase_ic`.`mfr_id`, 
     `icbase_ic`.`sups` FROM `icbase_ic` WHERE `icbase_ic`.`id` = 21 ; args=(21,)
>>> ic.partno
u'880'
>>> ic.sups

For you model, Obviously just Person.objects.get(first_name="abc") has database access.

But if the field is ForeignKey ManyToManyField or other relationship field, it will has database access.

>>> ic.mfr
(0.030) SELECT `icbase_mfr`.`id`, `icbase_mfr`.`name`, `icbase_mfr`.`cn_name`, `icbase_mfr`.`url`, `icbase_mfr`.`description`, `icbase_mfr`.`productcount`, `icbase_mfr`.`parent_id`, `icbase_mfr`.`logo_path`, `icbase_mfr`.`active` FROM `icbase_mfr` WHERE `icbase_mfr`.`id` = 99 ; args=(99,)
<Mfr: Keystone Electronics>

I am sorry for my poor English.

Upvotes: 2

Related Questions