How does Django's ORM manage to fetch Foreign objects when they are accessed

后端 未结 3 1885
北海茫月
北海茫月 2021-01-31 04:47

Been trying to figure this out for a couple of hours now and have gotten nowhere.

class other(models.Model):
    user = models.ForeignKey(User)


others = other.         


        
3条回答
  •  一生所求
    2021-01-31 05:25

    Properties can be used to implement this behaviour. Basically, your class definition will generate a class similar to the following:

    class other(models.Model):
        def _get_user(self):
            ## o.users being accessed
            return User.objects.get(other_id=self.id)
    
        def _set_user(self, v):
            ## ...
    
        user = property(_get_user, _set_user)
    

    The query on User will not be performed until you access the .user of an 'other' instance.

提交回复
热议问题