简体   繁体   English

如何在Django中添加与通用外键的unique_together

[英]How to add unique_together with generic foreign key in Django

I am not sure if I am doing it wrong or there is some issue when handling unique constraint when working with GenericForeign Relations in Django. 我不确定我是做错了还是在Django中使用GenericForeign Relations处理唯一约束时出现问题。

When I try to save an object (in Admin for example) I get unique constraint error (raises 500) form database but not ValidationError on Admin (UI). 当我尝试保存一个对象时(例如在Admin中),我从数据库中收到唯一的约束错误(提高500),但在Admin(UI)上没有ValidationError。

Below is my code snippet, 以下是我的代码段,

I have one generic relation model as below, 我有一个如下的通用关系模型,

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')

And my other model using it is, 我使用它的另一个模型是

class MyModel(models.Model):
    name = models.CharField(max_length=60, db_index=True)
    targeting = GenericRelation('Targeting')

Exception Raised: 引发异常:

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.

Is there something wrong with way I implemented it ? 我的实现方式有问题吗? or something is not meant to used like this ? 还是不该使用这样的东西?

Any sort of help is really appreciated. 真的很感谢任何帮助。 Thanks 谢谢

You won't receive ValidationError here, because it can't be validated without additional query and django won't create that query by itself. 您不会在这里收到ValidationError,因为没有其他查询就无法验证它,并且django不会自行创建该查询。 If you need to have that validation, you need to write it by yourself. 如果需要进行验证,则需要自己编写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM