Nalutas: ang django ay nag-save ng isa pang data ng klase habang nagse-save ng isang klase

Kapag nagse-save ng klase, sine-save ni Django ang lahat ng mga variable ng instance at pamamaraan ng klase. Maaari itong magdulot ng mga problema kung gusto mong mag-save ng isa pang data ng klase habang sine-save ang klase.

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

s ea si er an d mor e re ada ble โ€ฆ . h tt p : // w iki . pyt hon . o g/ moi n/ Py thon Deco rato rs #Wh at_ is _ a _ Deco rato r โ€ฆ ngunit malamang na mangyari ito sa kanyang araw ๐Ÿ™‚ G ood l uck ! Bria n Karr bk arr @ bk arr consu lti ng.. com h ttp: //www. bk arr consu lti ng .. com

Makipagtulungan sa klase

Sa Django, nakikipagtulungan ka sa mga modelo upang gawin at pamahalaan ang iyong data. Ang isang modelo ay isang representasyon ng data sa iyong aplikasyon. Maaaring simple o kumplikado ang mga modelo, at maaaring maglaman ng anumang uri ng data na kailangan mo.

Upang lumikha ng isang modelo sa Django, ginagamit mo ang django model() function. Ang function na ito ay tumatagal ng dalawang argumento: ang pangalan ng modelo at isang listahan ng mga field na bumubuo sa modelo. Ang mga field ay tinukoy bilang mga variable ng Python na kumakatawan sa mga piraso ng data sa iyong modelo. Maaari mong tukuyin ang mga patlang alinman bilang mga string o bilang mga bagay.

Para gumawa ng bagong instance ng isang modelo, ginagamit mo ang django create_model() function. Kinukuha ng function na ito ang pangalan ng modelo at isang instance ng FieldType object bilang mga argumento nito. Tinutukoy ng bagay na FieldType kung paano dapat i-populate ang mga field sa isang modelo. May tatlong uri ng mga bagay na FieldType: string, integer, at float. Maaari mo ring tukuyin ang mga custom na FieldType object gamit ang django field_type() function.

Kapag nakagawa ka na ng modelo, magagamit mo ito upang mag-imbak ng data sa iyong application. Upang gawin ito, ginagamit mo ang django save() function upang magsulat ng data sa iyong database at ang django save_all() function upang magsulat ng data sa lahat ng mga modelo sa iyong application nang sabay-sabay. Maaari mo ring gamitin ang django update() function upang i-update ang data sa iyong database batay sa mga pagbabagong ginawa sa mga modelo sa iyong application.

Kaugnay na mga post:

Mag-iwan ng komento