国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

關于Django外鍵賦值問題詳解

2020-02-16 02:03:15
字體:
來源:轉載
供稿:網友

本文主要給大家介紹關于Django外鍵賦值的相關內容,分享出來供大家參考學習,在開始之前,我們先來看一段代碼:

class Article(models.Model): title = models.CharField(max_length=1024, default='') ... def __str__(self):  return 'Article pk:%d %s' % (self.pk, self.title[:30])class ArticleContent(models.Model): article = cached_fields.OneToOneField(Article) ...

寫代碼的的時候,發現了一個很奇怪的現象,當我給一個instance的外鍵(以_id結尾)賦值(數字)的時候 ,這個外鍵對應的instance的值并不會改變。

In [44]: ac = ArticleContent.objects.get(article_id=14269)In [45]: ac.article_idOut[45]: 14269In [46]: ac.article_id = 14266In [47]: ac.save()In [48]: ac.articleOut[48]: <Article: Article pk:14266 EC: Russia, Ukraine to Meet in>In [49]: ac.article.pkOut[49]: 14266

如上面的代碼所示,為了找到答案,我翻了一下Django的源碼:

django/db/models/fields/related_descriptors.py   def __get__(self, instance, cls=None):   """   Get the related instance through the forward relation.   With the example above, when getting ``child.parent``:   - ``self`` is the descriptor managing the ``parent`` attribute   - ``instance`` is the ``child`` instance   - ``cls`` is the ``Child`` class (we don't need it)   """   if instance is None:    return self   # The related instance is loaded from the database and then cached in   # the attribute defined in self.cache_name. It can also be pre-cached   # by the reverse accessor (ReverseOneToOneDescriptor).   try:    rel_obj = getattr(instance, self.cache_name)   except AttributeError:    val = self.field.get_local_related_value(instance)    if None in val:     rel_obj = None    else:     qs = self.get_queryset(instance=instance)     qs = qs.filter(self.field.get_reverse_related_filter(instance))     # Assuming the database enforces foreign keys, this won't fail.     rel_obj = qs.get()     # If this is a one-to-one relation, set the reverse accessor     # cache on the related object to the current instance to avoid     # an extra SQL query if it's accessed later on.     if not self.field.remote_field.multiple:      setattr(rel_obj, self.field.remote_field.get_cache_name(), instance)    setattr(instance, self.cache_name, rel_obj)   if rel_obj is None and not self.field.null:    raise self.RelatedObjectDoesNotExist(     "%s has no %s." % (self.field.model.__name__, self.field.name)    )   else:    return rel_obj

注釋得非常到位,當我們請求ac.article的時候,會先去檢查對應的cache(在這里是_article_cache,感興趣可以去看cache_name的生成規則,就是外鍵名前面加下劃線,后面加cache)存不存在,如果不存在那么就進行數據庫請求,請求完之后會保存到cache中。

我們再看看__set__ ,代碼太長就不貼了(就在

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 滦南县| 独山县| 宁河县| 台东市| 东明县| 通许县| 鄂伦春自治旗| 新巴尔虎左旗| 台中县| 永州市| 盐亭县| 班玛县| 静乐县| 巴彦淖尔市| 建昌县| 星座| 高雄市| 靖州| 钟祥市| 双峰县| 喀喇沁旗| 黎平县| 徐州市| 波密县| 邵阳县| 河北省| 天水市| 吴川市| 永宁县| 双牌县| 平远县| 河南省| 通化市| 健康| 荆州市| 苏州市| 广宁县| 双流县| 邳州市| 神池县| 闽侯县|