我有一个 Django3 项目(我的第一个),其模型名为 Product,该模型与 Location (ProductLocation) 具有 m2m 关系。 ProductLocations 通过 ProductLocationCategory 与 Category 有 m2m 关系)。我希望提取具有 ProductLocation.active = True 和 ProductLocation.active_last_run = False 的所有产品。为此,我使用以下代码:
new_products = Product.objects.filter(locations__active=True, locations__active_last_run=False)
我从Django help docs那里借来的。 Product、ProductLocation 和 ProductLocationCategory 如下所示:
class Product(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
image = models.CharField(max_length=500, null=True, blank=True)
locations = models.ManyToManyField('Location', null=True, through='ProductLocation')
active = models.BooleanField(default=True, blank=True)
class ProductLocation(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE)
location = models.ForeignKey('Location', on_delete=models.CASCADE)
categories = models.ManyToManyField('Category', null=True, through='ProductLocationCategory')
active = models.BooleanField(default=True, blank=True)
active_last_run = models.BooleanField(default=False, blank=True)
class ProductLocationCategory(models.Model):
product_location = models.ForeignKey('ProductLocation', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
active = models.BooleanField(default=True, blank=True)
active_last_run = models.BooleanField(default=False, blank=True)
class Location(models.Model):
name = models.CharField(max_length=100)
...
active = models.BooleanField(default=True, blank=True)
我收到的完整(er)错误如下:
File "/home/user/projects/myproject/app/product/views.py", line 24, in location_detail
...
new_products = Product.objects.filter(locations__active=True, locations__active_last_run=False)
...
django.core.exceptions.FieldError: Related Field got invalid lookup: active_last_run
我已验证所有迁移都已运行,字段在数据库中,我创建了多个迁移添加和删除字段。如果我只跑:
new_products = Product.objects.filter(locations__active=True)
然后视图将正常完成。我已经在 SO 上搜索了大多数类似的问题,以了解我现在所处的位置,其余的大部分内容都在使用以下内容:
new_products = Product.objects.filter(locations__name__icontains = 'text')
这会起作用:
ProductLocation.objects.filter(active_last_run=False)
我确定我遗漏了一些简单的东西,但我看不到它。感谢您的帮助!
编辑:
添加了位置模型,尽管我忽略了地址字段,因为我认为它们不相关。
补充一下,数据的大体结构如下:
产品->位置->类别
一个产品可以属于多个位置,每个位置可以将该产品归入多个类别(特色等)。