社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

为什么选择instance.profile.save()django python

Asif • 5 年前 • 1693 次点击  

我很难理解这段代码。

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

我们为什么要执行 instance.profile.save() 给你,给你 post_save 信号是用户已经保存的证明,并且已经创建了与该用户关联的配置文件?

请帮助我理解!谢谢

编辑: 在里面 instance.profile.save()。 profile 内置关键字

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38221
 
1693 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Pedro
Reply   •   1 楼
Pedro    6 年前

似乎第一个信号是在创建用户时创建配置文件。在一次调用中更新用户和配置文件的第二个调用,例如:

user.first_name = 'John'
user.last_name = 'Smith'
user.profile.age = 30
user.save()  # user and profile are updated in one call

所以你不必这么做:

user.profile.save()