我不明白为什么Django ORM会给我这个prefetch_related()的错误

nimxete2  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(91)

在我的Django应用程序中有以下数据模型:

class Company(models.Model):
    company_name = models.CharField(max_length=255)
    company_url = models.URLField(max_length=2048, blank=True, null=True)
    ...
    class Meta:
        db_table = 'company_table'

class PricingPlan(models.Model):
    plan_name = models.CharField(max_length=255, blank=True, null=True)
    ...
    company = models.ForeignKey(Company, related_name='pricing_plans', on_delete=models.CASCADE, blank=True, null=True)
    class Meta:
        db_table = 'pricing_plan_table'

class Feature(models.Model):
    feature_name = models.TextField(blank=True, null=True)
    plans = models.ManyToManyField(PricingPlan, related_name='features', blank=True)
    class Meta:
        db_table = 'feature_table'

class WebData(models.Model):
    company = models.OneToOneField(Company, related_name='web_data', on_delete=models.CASCADE)
    version = models.IntegerField(blank=True, null=True)
    ...
    class Meta:
        db_table = 'web_data_table'

字符串
现在,我想像这样查询DB:

queryset = queryset.select_related('web_data').prefetch_related('pricing_plans', 'pricing_plans__features')


但得到这个错误:

django.db.utils.ProgrammingError: relation "feature_table_plans" does not exist
LINE 1: ...e"."feature_name" FROM "feature_table" INNER JOIN "feature_t...


有什么解决办法吗?

tktrz96b

tktrz96b1#

尝试:

from django.db.models import Prefetch
queryset = queryset.select_related('web_data').prefetch_related(Prefetch('pricing_plans', queryset=PricingPlan.objects.prefetch_related('features')))

字符串

相关问题