django之relacted.py(探秘django的關聯field)


生成model類對象時,傳入的每個field對象都會調用其contribute_to_class函數,生成對應的屬性。

def contribute_to_class(self, cls, name, virtual_only=False):

        super(RelatedField, self).contribute_to_class(cls, name, virtual_only=virtual_only)

        self.opts = cls._meta

        if not cls._meta.abstract:
            if self.remote_field.related_name:
                related_name = force_text(self.remote_field.related_name) % {
                    'class': cls.__name__.lower(),
                    'app_label': cls._meta.app_label.lower()
                }
                self.remote_field.related_name = related_name

            def resolve_related_class(model, related, field):#如果是關聯field的話,會對關聯model產生動作
                field.remote_field.model = related
                field.do_related_class(related, model)
            lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
field.do_related_class(related, model)
def do_related_class(self, other, cls):
        self.set_attributes_from_rel()
        self.contribute_to_related_class(other, self.remote_field)

def set_attributes_from_rel(self):
        self.name = (
            self.name or
            (self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name)
        )
        if self.verbose_name is None:
            self.verbose_name = self.remote_field.model._meta.verbose_name
        self.remote_field.set_field_name()#設置了遠程field的名字

def contribute_to_related_class(self, cls, related):#related為遠程filed
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
#為關聯model設置了一個屬性:category = models.ForeignKey(Category, related_name='forums'
#Category.category_id的屬性related_accessor_class,然后就可以調用related_accessor_class
#add,remove等函數

setattr(cls, related.get_accessor_name(), self.related_accessor_class(related))
# While 'limit_choices_to' might be a callable, simply pass # it along for later - this is too early because it's still # model load time. if self.remote_field.limit_choices_to: cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to)

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com