我需要检查为相同的内容添加的记录(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做些什么?可以这样做,如果是这样的话?
答案 0 :(得分:2)
你可以用我能想到的多种方式之一来做到这一点:
pre_save
信号save()
方法Meta
属性上添加唯一约束。 最干净的方法是使用模型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", ]