1

您好我有一个问题,我想将外键链接到模型的相关对象,换句话说,我想将外键链接到未加载对象的字段。

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, on_delete=models.SET_NULL, 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', on_delete=models.SET_NULL, 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 来做这样的关系?

4

1 回答 1

0

我认为您实际上不需要添加其他关系,因为您可以通过 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>'
        )
    )
)

由于关系基于索引的外键 - 这样的查询不应该对性能产生明显的影响(尽管它可能看起来有点尴尬)

于 2021-05-08T13:41:05.210 回答