Résolu : Django enregistre les données d'une autre classe lors de l'enregistrement d'une classe

Lors de l'enregistrement d'une classe, Django enregistre toutes les variables d'instance et méthodes de la classe. Cela peut causer des problèmes si vous souhaitez enregistrer les données d'une autre classe tout en sauvegardant la classe.

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

plus facile et plus lisible … . h tt p : // wiki . pyt chéri . ou g/ moi n/ Py thon Deco rato rs #Wh at_ is _ a _ Deco ratator … mais c'est probablement quelque chose pour un autre jour 🙂 Bonne chance ! Bria n Karr bk arr @ bk arr consu lti ng .. com h ttp : / / www . bk arr consu lti ng .. com

Travailler avec la classe

Dans Django, vous travaillez avec des modèles pour créer et gérer vos données. Un modèle est une représentation des données dans votre application. Les modèles peuvent être simples ou complexes et peuvent contenir tout type de données dont vous avez besoin.

Pour créer un modèle dans Django, vous utilisez la fonction django model(). Cette fonction prend deux arguments : le nom du modèle et une liste de champs qui composent le modèle. Les champs sont définis comme des variables Python qui représentent des éléments de données dans votre modèle. Vous pouvez définir des champs sous forme de chaînes ou d'objets.

Pour créer une nouvelle instance d'un modèle, vous utilisez la fonction django create_model(). Cette fonction prend le nom du modèle et une instance de l'objet FieldType comme arguments. L'objet FieldType définit la manière dont les champs d'un modèle doivent être remplis. Il existe trois types d'objets FieldType : string, integer et float. Vous pouvez également définir des objets FieldType personnalisés à l'aide de la fonction django field_type().

Une fois que vous avez créé un modèle, vous pouvez l'utiliser pour stocker des données dans votre application. Pour ce faire, vous utilisez la fonction django save() pour écrire des données dans votre base de données et la fonction django save_all() pour écrire des données dans tous les modèles de votre application à la fois. Vous pouvez également utiliser la fonction django update() pour mettre à jour les données de votre base de données en fonction des modifications apportées aux modèles de votre application.

Articles connexes

Laisser un commentaire