Django模型通过一到一个模型字段过滤
想象一下,我有这两个模型:
class A(models.Model):
name = models.CharField(max_length=150)
class B(models.Model):
a = models.OneToOneField(
to=A, on_delete=models.CASCADE, null=False
)
location = models.CharField(max_length=100)
我希望B模型的QuerySet被A.NAME和位置过滤,
例如:
select * from B join A
on B.a.pk = A.pk
where A.name="name" and B.location="location";
我尝试过,但它给出了一个错误:
query=B.objects.filter(a.name=name)
Imagine I have those two models:
class A(models.Model):
name = models.CharField(max_length=150)
class B(models.Model):
a = models.OneToOneField(
to=A, on_delete=models.CASCADE, null=False
)
location = models.CharField(max_length=100)
And I want a queryset of B model to be filtered by the a.name and location,
like this:
select * from B join A
on B.a.pk = A.pk
where A.name="name" and B.location="location";
I tried this but it gives an error:
query=B.objects.filter(a.name=name)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仔细阅读文档。 U可以使用双重下划线访问相关字段。因此,在您的情况下,DAT将是:
Read the documentation carefully. U can access related fields with double underscore. So in your case dat will be: