微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django外键未加载对象

如何解决Django外键未加载对象

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

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>'
        )
    )
)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。