Django 在一个模型中用于一般关系的两个不同字段
我的项目中有一个带有通用外键的模型,用于定义这些模型的图像:Django 在一个模型中用于一般关系的两个不同字段,django,django-models,django-orm,Django,Django Models,Django Orm,我的项目中有一个带有通用外键的模型,用于定义这些模型的图像: class GenericImage(models.Model): image = ImageField( ) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, blank=True, null=True ) object_id = m
class GenericImage(models.Model):
image = ImageField(
)
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
blank=True,
null=True
)
object_id = models.PositiveIntegerField(
blank=True,
null=True
)
content_object = GenericForeignKey(
'content_type',
'object_id'
)
我想提供此模型的两个不同链接,一个是主图像的generirelation
,另一个是其他图像的generirelation
class MyModel(models.Model):
images = GenericRelation(
GenericImage,
)
main_image = GenericRelation(
GenericImage,
)
首先想到的是将布尔字段main_image
添加到generiimage
模型中,并覆盖clean
方法:
class GenericImage(models.Model):
...
main_image = models.BooleanField(
default=False
)
def clean(self):
obj = self.content_object
if self.main_image and obj:
if obj.images.filter(main_image=True).exists():
raise ValidationError('main image must be unique!')
但它将验证逻辑从主模型中分离出来,每当我想更改main\u image
有没有什么优雅的解决方案可以解决我的问题,或者我根本不需要
ContentType框架
,m2m
与中间表的链接会更好。对main\u image
使用ForeignKey,对image使用m2m