django 中的复杂查找

发布于 2024-12-16 14:59:08 字数 740 浏览 2 评论 0原文

我有一个具有多个字段的类,其中两个是多对多字段:

class someClass(models.Model):
    field1 = ...
    field2 = ...
    field3 = ...
    field4 = models.ManytoManyField(...)
    field5 = models.ManytoManyField(...)

我最初希望稍后使用 someClass.objects.get(...)

someClass.objects.get(field1=..., field2=..., ...)

我会还想限制 field4 和 field5 返回的 someClass 。我假设我无法在 .get() 调用中执行此操作,因为这些表示可以采取多种形式的多对多关系。

当我一直在寻找一个唯一的 someClass 时,我可以访问与 field1-field3 中表示的对象相对应的几个变量,以及与field4 和 field5 中表示的对象。这些一起应该描述一个独特的实例。

接受我可能必须在一系列 .filter() 中执行此操作,对于我来说,获取我的数据(再次)的单个 someClass 对象的最佳方法是什么? ,field1-field3各有一个变量,field4和field5有两个列表)描述了什么?

I have a class that has a number of fields, two of which are many-to-many fields:

class someClass(models.Model):
    field1 = ...
    field2 = ...
    field3 = ...
    field4 = models.ManytoManyField(...)
    field5 = models.ManytoManyField(...)

I was originally hoping to use someClass.objects.get(...) later on:

someClass.objects.get(field1=..., field2=..., ...)

I would also like to limit the someClasses that get returned by field4 and field5 as well. I assume that I cannot do this in a .get() call because these represent many-to-many relationships that can take many forms.

At the time that I would have been looking to find a unique someClass, I would have access to several variables that correspond to objects represented in field1-field3, as well as two short lists of objects that correspond to the objects represented in field4 and in field5. These together should describe a unique instance.

Accepting that I may have to do this in a series of .filter()s, what is the best way for me to obtain the single someClass object that my data (again, one variable apiece for field1-field3 and two lists for field4 and field5) describes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

用心笑 2024-12-23 14:59:08

我认为答案正如您所期望的那样明显......

您绝对不能在此处使用 get 因为 m2m s - 您必须链接过滤器以排除结果包含不精确的 m2m 匹配。

query = someClass.objects.filter(field1=field1, field2=field2, field3=field3)

for item in list1:
   query = query.filter(foo=item)

for item in list2:
   query = query.filter(bar=item)

# substitute with fancy python as you wish.

I think the answer is as obvious as you expect...

You definitely can't use get here because of the m2ms - you have to chain the filters to exclude results that contain inexact m2m matches.

query = someClass.objects.filter(field1=field1, field2=field2, field3=field3)

for item in list1:
   query = query.filter(foo=item)

for item in list2:
   query = query.filter(bar=item)

# substitute with fancy python as you wish.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文