Django检查重复的content_type和object_id

时间:2013-06-04 15:31:05

标签: django django-models

我需要检查为相同的内容添加的记录(content_type和object_id),以确保在保存时不将其复制到数据库。

  class objectHere(models.Model):
        """
        Notes:


        See: http://www.screamingatmyscreen.com/2012/6/django-and-generic-relations/
        """
        content_type = models.ForeignKey(ContentType, help_text="Represents the name of the model")
        object_id = models.PositiveIntegerField(help_text="stores the object id")
        content_object = generic.GenericForeignKey('content_type', 'object_id')

        reason = models.CharField(max_length=60)

        request_made = models.DateTimeField(auto_now_add=True,
                                       help_text="Shows when object was created.")

我在想用pre_save做些什么?可以这样做,如果是这样的话?

2 个答案:

答案 0 :(得分:2)

你可以用我能想到的多种方式之一来做到这一点:

  1. pre_save信号
  2. 覆盖模型'save()方法
  3. 在模型的Meta属性上添加唯一约束。
  4. 在视图或表单的清洁方法中检查
  5. 最干净的方法是使用模型Meta上的unique_together。但是,如果您不想针对模型运行迁移,如果存在解决错误所需的某些用户操作,我建议使用view / form的clean方法。

答案 1 :(得分:1)

您可以在模型上使用unique_together meta option

class MyObject(models.Model): 
    content_type = models.ForeignKey()
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    ....

    class Meta:
        unique_together = ["content_type", "object_id", ]