可以通过 ForeignKey related_name 对象过滤查询集吗?
Possible to filter a queryset by its ForeignKey related_name objects?
我有一个简单的模型:
class Object(models.Model):
name = CharField()
root = ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL)
我创建了几个对象:
parent1 = Object.create(name="parent1")
o1 = Object.create(name="1", root=parent1")
parent1.object_set.all() # Returns queryset with o1
是否可以通过外键的 related_name 对象(即 object_set
)过滤查询集?类似于:
Object.objects.filter(object_set__name="1") # To return parent1
我收到以下错误:Cannot resolve keyword 'object_set' into field.
我知道我可以 Object.object.get(name="1").root
但这会导致额外的查询,这些查询在我的特定用例中可能会真正加起来。
使用:
Object.objects.filter(object__name="1")`
而不是:
Object.objects.filter(object_set__name="1")
中描述了如何确定查找名称
While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.
我有一个简单的模型:
class Object(models.Model):
name = CharField()
root = ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL)
我创建了几个对象:
parent1 = Object.create(name="parent1")
o1 = Object.create(name="1", root=parent1")
parent1.object_set.all() # Returns queryset with o1
是否可以通过外键的 related_name 对象(即 object_set
)过滤查询集?类似于:
Object.objects.filter(object_set__name="1") # To return parent1
我收到以下错误:Cannot resolve keyword 'object_set' into field.
我知道我可以 Object.object.get(name="1").root
但这会导致额外的查询,这些查询在我的特定用例中可能会真正加起来。
使用:
Object.objects.filter(object__name="1")`
而不是:
Object.objects.filter(object_set__name="1")
中描述了如何确定查找名称
While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.