如果我有两个模特
class modelA(models.Model):
# properties...
class modelB(models.Model):
# properties我想把这两个模型都放到一个images字段中,然后如何编写图像模型呢?如果只是一个,我想就像:
class Image(models.Model):
image = models.ForeignKey(modelA)所以,如果我也希望modelB有图像,那该怎么做呢?我要写ImageA和ImageB吗?
发布于 2016-05-11 02:52:29
看起来你想要使用通用外键
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Image(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')现在,您的Image模型可以具有其他任何一个模型的外键,并且可以有与每个对象相关联的多个图像。我所链接到的文档说明了如何使用此设置和查询对象等。
有关如何限制这一点,请参见这个答案,以便您可以将外键仅限于特定的模型。
发布于 2016-05-11 02:44:41
用另一种方式处理这段关系。
class Image(models.Model):
# properties
class modelA(models.Model):
image = models.ForeignKey(Image, vars=vals)
class modelB(models.Model):
image = models.ForeignKey(Image, vars=vals)然后,您可以查询为
modelB.image
modelA.image
image.modelA_set.all()
image.modelB_set.all()https://stackoverflow.com/questions/37152200
复制相似问题