已解决:django 在保存一个类的同时保存另一个类的数据

当保存一个类时,Django 会保存该类的所有实例变量和方法。 如果你想在保存类的同时保存另一个类数据,这可能会导致问题。

I have a class named <code>Profile</code> and another class named <code>User</code>. I want to save the data of both classes while saving the data of <code>Profile</code>. How can I do this?
<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # Save User here

        return self
</code>


A:

You can access the related object with <code>.user</code>, so you can just call <code>.save()</code>:  (Note that you don't need to return anything from your override.)  If you're using Django 2+ and have set up your model correctly with a custom User model, then this will work automatically:  https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#extending-the-existing-user-model  Otherwise you'll need to add an import for your custom User model at the top of your file:   from .myapp import MyCustomUserModel as User .   (Or wherever it is in your project.)   If you're using Django 1.* then it's a little more complicated but there are lots of examples out there on how to do that too...   Good luck!     Let me know if this helps... 🙂     -Brian Karr  bkarr@bkarrconsulting.com  http://www.bkarrconsulting.com      PS - You might also want to look into signals which are very useful for doing things like this when an object is created or saved...   https://docs.djangoproject.com/en/2.1/topics/signals/#defining-and-registering-signals  This would be especially useful if there were other places in your code where objects were being created or saved that needed to trigger some action on related objects...     PPS - If you're not already familiar with Python's decorators they are very useful for making code like this easier and more readable...   https://wiki.python.org/moin/PythonDecorators#What_is_a_Decorator ...but that's probably something for another day 🙂      Good luck!       Brian Karr    bkarr@bkarrconsulting..com    http://www..bkarrconsulting..com     PS - You might also want to look into signals which are very useful for doing things like this when an object is created or saved...   https://docs..djangoproject..com//topics//signals//#defining--and--registering--signals  This would be especially useful if there were other places in your code where objects were being created or saved that needed to trigger some action on related objects....     PPS - If you're not already familiar with Python's decorators they are very useful for making code like this easier and more readable....   https:/wiki..python..org//moin//PythonDecorators#What_is_a_Decorator ...but that's probably something for another day 🙂      Good luck!       Brian Karr    bkarr@bkarrconsulting....com    http:/www....bkarrconsulting....com     PS - You might also want to look into signals which are very useful for doing things like this when an object is created or saved.....   https:/docs.....djangoproject.....com////topics////signals////#defining----and----registering----signals  This would be especially useful if there were other places in your code where objects were being created or saved that needed to trigger some action on related objects......     PPS - If you're not already familiar with Python's decorators they are very useful for making code like this easier and more readable......   https:/wiki......python......org////moin////PythonDecorators#What_is_a_Decorator ...but that's probably something for another day 🙂      Good luck!       Brian Karr    bkarr@bkarrconsulting.......com    http:/www.......bkarrconsulting.......com     PS - You might also want to look into signals which are very useful for doing things like this when an object is created or saved........   https:/docs........djangoproject........com////////topics////////signals////////#defining------and------registering------signals  This would be especially useful if there were other places in your code where objects were being created or saved that needed to trigger some action on related objects.........     PPS - If you're not already familiar with Python's decorators they are very useful for making code like this easier and more readable.........   https:/wiki.........python.........org////////moin////////PythonDecorators#What_is_a_Decorator ...but that's probably something for another day 🙂      Good luck!       Brian K arr    b k arr @ b k arr consulting ........ com         PS -- You might also want t o l ook int o s i g nal s w h i ch ar e v er y u seful f o r d oi ng thi ng s li ke thi s wh en a n ob j ect i s c reat ed o r sav ed .... .. . h tt p : / / doc s . djan go pr ojec t . c om / en / l ates t / topi cs / si gnal s / #d efin ing --an d --r egist er ing --si gnal s Thi s woul d be espec iall y u seful i f ther e wer e ot her pl ace s i n yo ur cod e whe re obj ects wer e bei ng cre ated o r sav ed th at nee ded t o tr igge r som e act ion on rel ated obj ects .... .. . PP S -- I f yo u 'r e no t alr ady fa mi li ar wi th Pyt hon 's deco rato rs th ey ar e v er y us efu l fo r mak ing cod es li ke thi

更易读,更易读…… h tt p : // w iki 。 Python 。 或 g/ moi n/ Python Deco rato rs #Wh at_ 是 _ a _ Deco rator ……但这可能是她某天的一些事情🙂祝你好运! Bria n Karr bk arr @ bk arr consu lti ng .. com h ttp: // www . bk arr consulting .. com

与班级一起工作

在 Django 中,您使用模型来创建和管理数据。 模型是应用程序中数据的表示。 模型可以简单也可以复杂,并且可以包含您需要的任何类型的数据。

要在 Django 中创建模型,您可以使用 django model() 函数。 此函数有两个参数:模型名称和构成模型的字段列表。 字段被定义为代表模型中数据片段的 Python 变量。 您可以将字段定义为字符串或对象。

要创建模型的新实例,您可以使用 django create_model() 函数。 此函数将模型名称和 FieldType 对象的实例作为其参数。 FieldType 对象定义应如何填充模型中的字段。 共有三种类型的 FieldType 对象:字符串、整数和浮点数。 您还可以使用 django field_type() 函数定义自定义 FieldType 对象。

创建模型后,您可以使用它在应用程序中存储数据。 为此,您可以使用 django save() 函数将数据写入数据库,并使用 django save_all() 函数一次将数据写入应用程序中的所有模型。 您还可以使用 django update() 函数根据对应用程序中的模型所做的更改来更新数据库中的数据。

相关文章:

发表评论