[Answered ]-When django model access DB

2๐Ÿ‘

โœ…

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.

๐Ÿ‘คlifeng.luck

Leave a comment