IT

Django : 일부 모델 필드가 서로 충돌하는 이유는 무엇입니까?

lottoking 2020. 5. 26. 07:53
반응형

Django : 일부 모델 필드가 서로 충돌하는 이유는 무엇입니까?


Users에 대한 2 개의 링크가 포함 된 개체를 만들고 싶습니다. 예를 들면 다음과 같습니다.

class GameClaim(models.Model):
    target = models.ForeignKey(User)
    claimer = models.ForeignKey(User)
    isAccepted = models.BooleanField()

그러나 서버를 실행할 때 다음 오류가 발생합니다.

  • 'target'필드 접근자는 관련 필드 'User.gameclaim_set'과 충돌합니다. 'target'의 정의에 related_name 인수를 추가하십시오.

  • 'claimer'필드 접근자는 관련 필드 'User.gameclaim_set'과 충돌합니다. 'claimer'의 정의에 related_name 인수를 추가하십시오.

오류가 발생하는 이유와 해결 방법을 설명해 주시겠습니까?


사용자에게 두 개의 외래 키가 있습니다. Django는 자동으로 User에서 GameClaim으로의 반전 관계를 자동으로 만듭니다 gameclaim_set. 그러나 두 개의 FK가 있기 때문에 두 가지 gameclaim_set속성이 있으므로 불가능합니다. 따라서 Django에게 역 관계에 사용할 이름을 알려 주어야합니다.

related_nameFK 정의에서 속성을 사용하십시오 . 예 :

class GameClaim(models.Model):
    target = models.ForeignKey(User, related_name='gameclaim_targets')
    claimer = models.ForeignKey(User, related_name='gameclaim_users')
    isAccepted = models.BooleanField()

User모델은 같은 이름을 가진 두 개의 필드, 하나 만들려고 GameClaims것을 가질 수 User는 AS를 target하고, 또 다른 GameClaims이는이 User과를 claimer. 에 대한 문서related_name 는 Django가 자동 생성 속성이 충돌하지 않도록 속성 이름을 설정하는 방법입니다.


OP는 추상 기본 클래스를 사용하지 않지만 ... 그렇다면 FK에서 related_name을 하드 코딩하면 (예 : ..., related_name = "myname") 여러 가지 충돌 오류가 발생합니다. -기본 클래스에서 상속 된 각 클래스마다 하나씩 아래에 제공된 링크에는 해결 방법이 포함되어 있지만 간단하지만 분명하지는 않습니다.

장고 문서에서 ...

ForeignKey 또는 ManyToManyField에서 related_name 속성을 사용하는 경우 항상 필드의 고유 한 역방향 이름을 지정해야합니다. 이 클래스의 필드는 매번 속성 (related_name 포함)에 대해 정확히 동일한 값으로 각 하위 클래스에 포함되므로 일반적으로 추상 기본 클래스에서 문제가 발생합니다.

자세한 내용은 여기를 참조하십시오 .


때로는 related_name상속을 사용할 때마다 추가 서식을 사용해야 할 때가 있습니다 .

class Value(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=5)
    animal = models.ForeignKey(
        Animal, related_name="%(app_label)s_%(class)s_related")

    class Meta:
        abstract = True

class Height(Value):
    pass

class Weigth(Value):
    pass

class Length(Value):
    pass

여기서 충돌은 없지만 related_name은 한 번 정의되며 Django는 고유 한 관계 이름을 생성합니다.

그런 다음 Value 클래스의 어린이는 다음에 액세스 할 수 있습니다.

herdboard_height_related
herdboard_lenght_related
herdboard_weight_related

장고 프로젝트에 응용 프로그램으로 하위 모듈을 추가 할 때 가끔 다음과 같은 구조가 나타납니다.

myapp/
myapp/module/
myapp/module/models.py

INSTALLED_APPS에 다음을 추가하면 :

'myapp',
'myapp.module',

장고는 myapp.mymodule models.py 파일을 두 번 처리하고 위의 오류를 발생시키는 것으로 보입니다. INSTALLED_APPS 목록에 기본 모듈을 포함시키지 않으면이 문제를 해결할 수 있습니다.

'myapp.module',

myapp대신을 포함 myapp.module하면 모든 데이터베이스 테이블이 잘못된 이름으로 작성되므로 올바른 방법으로 보입니다.

I came across this post while looking for a solution to this problem so figured I'd put this here :)


Just adding to Jordan's answer (thanks for the tip Jordan) it can also happen if you import the level above the apps and then import the apps e.g.

myproject/ apps/ foo_app/ bar_app/

So if you are importing apps, foo_app and bar_app then you could get this issue. I had apps, foo_app and bar_app all listed in settings.INSTALLED_APPS

And you want to avoid importing apps anyway, because then you have the same app installed in 2 different namespaces

apps.foo_app and foo_app

참고URL : https://stackoverflow.com/questions/1142378/django-why-do-some-model-fields-clash-with-each-other

반응형