장고 모델 () vs. Model.objects.create () BarModel.objects.create() 두 번째

두 명령을 실행하는 것의 차이점은 무엇입니까?

foo = FooModel()

bar = BarModel.objects.create()

두 번째 BarModel는 데이터베이스에 즉시 a 를 작성하는 반면,에 대해 데이터베이스 에 추가 FooModel하려면 save()메소드를 명시 적으로 호출해야합니까?



답변

https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects

단일 단계에서 객체를 생성하고 저장하려면이 create()방법을 사용하십시오 .


답변

두 구문은 동일하지 않으며 예기치 않은 오류가 발생할 수 있습니다. 차이점을 보여주는 간단한 예는 다음과 같습니다. 모델이있는 경우 :

from django.db import models

class Test(models.Model):

    added = models.DateTimeField(auto_now_add=True)

그리고 첫 번째 객체를 만듭니다.

foo = Test.objects.create(pk=1)

그런 다음 동일한 기본 키로 객체를 만들려고합니다.

foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")

foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")

답변

업데이트 15.3.2017 :

나는 이것에 대해 장고 이슈를 열었고 여기에서 예비 적으로 받아 들여지는 것 같습니다 :
https://code.djangoproject.com/ticket/27825

내 경험은 Django와 함께 참조로 Constructor( ORM) 클래스 를 사용할 때 1.10.5데이터에 약간의 불일치가있을 수 있습니다 (즉, 작성된 객체의 속성이 캐스트 된 유형의 ORM 객체 속성 대신 입력 데이터의 유형을 얻을 수 있음) 예제 :

models

class Payment(models.Model):
     amount_cash = models.DecimalField()

some_test.pyobject.create

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor.objects.create(**actual_data)
            print(type(_obj.amount_cash)) # Decimal
            assert created
           objs.append(_obj)
        return objs

some_test.pyConstructor()

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor(**actual_data)
            print(type(_obj.amount_cash)) # Float
            assert created
           objs.append(_obj)
        return objs