해결됨: 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 : // 위키 . 피트 혼. 또는 g/ moi n/ Py thon Deco rator #Wh at_ is _ a _ Deco rator … 하지만 아마도 다른 날의 무언가일 것입니다 🙂 행운을 빕니다! Bria n Karr bk arr @ bk arr consulti ng .. com h ttp : // www. bk arr consulti ng .. com

클래스 작업

Django에서는 모델을 사용하여 데이터를 만들고 관리합니다. 모델은 애플리케이션의 데이터 표현입니다. 모델은 단순하거나 복잡할 수 있으며 필요한 모든 유형의 데이터를 포함할 수 있습니다.

Django에서 모델을 생성하려면 django model() 함수를 사용합니다. 이 함수는 모델 이름과 모델을 구성하는 필드 목록이라는 두 가지 인수를 사용합니다. 필드는 모델의 데이터 조각을 나타내는 Python 변수로 정의됩니다. 필드를 문자열 또는 개체로 정의할 수 있습니다.

모델의 새 인스턴스를 생성하려면 django create_model() 함수를 사용합니다. 이 함수는 모델의 이름과 FieldType 개체의 인스턴스를 인수로 사용합니다. FieldType 개체는 모델의 필드를 채우는 방법을 정의합니다. FieldType 개체에는 문자열, 정수 및 부동의 세 가지 유형이 있습니다. django field_type() 함수를 사용하여 사용자 정의 FieldType 객체를 정의할 수도 있습니다.

모델을 만든 후에는 이를 사용하여 애플리케이션에 데이터를 저장할 수 있습니다. 이렇게 하려면 django save() 함수를 사용하여 데이터베이스에 데이터를 쓰고 django save_all() 함수를 사용하여 애플리케이션의 모든 모델에 한 번에 데이터를 씁니다. 또한 django update() 함수를 사용하여 애플리케이션의 모델에 대한 변경 사항을 기반으로 데이터베이스의 데이터를 업데이트할 수 있습니다.

관련 게시물:

코멘트 남김