[python] 기본값없이 사용자 프로필에 nullable이 아닌 필드 ‘new_field’를 추가하려고합니다.

Django 1.7부터 South 또는 다른 마이그레이션 시스템을 사용할 필요가 없다는 것을 알고 있으므로 간단한 명령을 사용하고 있습니다. python manage.py makemigrations

그러나 내가 얻는 것은이 오류입니다.

You are trying to add a non-nullable field 'new_field' to userprofile without a default;
we can't do that (the database needs something to populate existing rows).

다음은 models.py입니다.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True)
    new_field = models.CharField(max_length=140)

옵션은 무엇입니까?



답변

기본값을 제공해야합니다.

new_field = models.CharField(max_length=140, default='SOME STRING')


답변

만약 는 초기 개발주기에 있고 상관 없어 현재에 대한 데이터베이스 데이터 당신은 그것을 제거하고 마이그레이션 할 수 있습니다. 하지만 먼저 마이그레이션 디렉터리를 정리하고 테이블 (django_migrations)에서 해당 행을 제거해야합니다.

rm  your_app/migrations/*

rm db.sqlite3
python manage.py makemigrations
python manage.py migrate


답변

한 가지 옵션은 ‘new_field’에 대한 기본값을 선언하는 것입니다.

new_field = models.CharField(max_length=140, default='DEFAULT VALUE')

또 다른 옵션은 ‘new_field’를 nullable 필드로 선언하는 것입니다.

new_field = models.CharField(max_length=140, null=True)

‘new_field’를 nullable 필드로 허용하기로 결정한 경우 ‘new_field’에 대한 유효한 입력으로 ‘입력 없음’을 허용 할 수 있습니다. 그런 다음 blank=True문도 추가해야 합니다.

new_field = models.CharField(max_length=140, blank=True, null=True)

심지어와 null=True및 / 또는blank=True 필요한 경우에는 기본 값을 추가 할 수 있습니다 :

new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)


답변

개발주기의 초기 단계라면 이것을 시도해 볼 수 있습니다.

해당 모델과 모든 사용법을 제거 / 주석하십시오. 마이그레이션을 적용합니다. 그러면 해당 모델이 삭제되고 모델이 다시 추가되고 마이그레이션이 실행되고 새 필드가 추가 된 깨끗한 모델이 생성됩니다.


답변

“웹 사이트”가 다음보다 비어있을 수있는 경우 new_field 것으로 설정해야합니다.

이제 new_field“웹 사이트”에서 값을 가져 오기 위해 비어 있는 경우 저장에 논리를 추가 하려면 다음 Model과 같이 저장 기능을 재정의 하면됩니다.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField(blank=True, default='DEFAULT VALUE')
    new_field = models.CharField(max_length=140, blank=True, default='DEFAULT VALUE')

    def save(self, *args, **kwargs):
        if not self.new_field:
            # Setting the value of new_field with website's value
            self.new_field = self.website

        # Saving the object with the default save() function
        super(UserProfile, self).save(*args, **kwargs)


답변

누구나를 설정하는 경우 ForeignKey기본값을 설정하지 않고 nullable 필드 만 허용 할 수 있습니다.

new_field = models.ForeignKey(model, null=True)

데이터베이스에 이미 데이터가 저장된 경우 기본값을 설정할 수도 있습니다.

new_field = models.ForeignKey(model, default=<existing model id here>)


답변

내부에 이미 데이터가있는 테이블에 대한 참조를 추가 할 수 없습니다.
변화:

user = models.OneToOneField(User)

에:

user = models.OneToOneField(User, default = "")

하다:

python manage.py makemigrations
python manage.py migrate

다시 변경 :

user = models.OneToOneField(User)

다시 마이그레이션하십시오.

python manage.py makemigrations
python manage.py migrate