问题描述
您好,我有一个问题,我想将外键链接到模型的相关对象,换句话说,我想将外键链接到未加载对象的字段。
class Category(models.Model):
...
filter_option_content_type = models.ForeignKey(ContentType,on_delete=models.SET_NULL,limit_choices_to=(
models.Q(app_label='catalog',model='FrameSize') |
models.Q(app_label='catalog',model='ShoeSize') |
models.Q(app_label='catalog',model='ClothSize')
),null=True)
...
class Product(models.Model):
...
category = models.ForeignKey(Category,null=True)
...
class ProductItem(models.Model):
...
model = models.ForeignKey(Product,verbose_name='Модель',on_delete=models.CASCADE,related_name='productitem')
size = models.ForeignKey('model.category.filter_option_content_type',null=True)
...
并且确定我收到此错误:
ValueError: Invalid model reference 'model.category.filter_option_content_type'. String model references must be of the form 'app_label.ModelName'
是否可以使用 GenericForeignKey 而不是 ForeignKey 来建立这样的关系?
解决方法
我认为您实际上不需要添加额外的关系,因为您可以通过 Product 访问您想要的字段:
item = ProductItem()
size = item.model.category.filter_option_content_type
如果您想使用此字段进行查询,它看起来像:
item = ProductItem.objects.filter(
model__in=Product.objects.filter(
category__in=Category.objects.filter(
filter_option_content_type='<your desired value of size>'
)
)
)
由于关系是基于索引的外键 - 这样的查询不应该对性能产生明显影响(尽管它可能看起来有点尴尬)