私が間違っているのか、それとも Django で GenericForeign Relations を使用する際に一意の制約を処理するときに問題があるのか わかりません。
オブジェクトを保存しようとすると (たとえば管理者で)、データベースから一意の制約エラー (500 が発生) が発生しますが、管理者 (UI) では ValidationError は発生しません。
以下は私のコードスニペットです、
以下のような一般的な関係モデルが 1 つあります。
class Targeting(models.Model):
TARGETING_CHOICES = (
('geo', "Geo targeting"),
('other', "Other targeting"),
)
targeting_type = models.CharField(max_length=64, choices=TARGETING_CHOICES, null=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id', 'targeting_type')
そして、それを使用している私の他のモデルは、
class MyModel(models.Model):
name = models.CharField(max_length=60, db_index=True)
targeting = GenericRelation('Targeting')
発生した例外:
duplicate key value violates unique constraint "mymodel_targeting_targeting_type_0dff10ee_uniq"
DETAIL: Key (targeting_type, content_type_id, object_id)=(geo, 18, 188) already exists.
私がそれを実装した方法に何か問題がありますか? または、このように使用するためのものではありませんか?
どんな種類の助けも本当に感謝しています。ありがとう