gpt4 book ai didi

Django 和编写包含大量连接的查询

转载 作者:行者123 更新时间:2023-12-02 01:49:59 25 4
gpt4 key购买 nike

我很难通过大量连接进行此类查询。我没有找到例子,但我想它们写起来并不复杂。就是有几个FK。

这里是models.py(不复杂)

class User(AbstractBaseUser, PermissionsMixin): # Django custom user model
# Some stuff

class CliProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)

class BizProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)

class Card(models.Model):
linked_client = models.ForeignKey(CliProfile, blank=True, null=True)

class Points(models.Model):
benef_card = models.ForeignKey(Card)
at_owner = models.ForeignKey(BizProfile)
creation_date = models.DateTimeField(auto_now_add=True)

模型的快速描述

  • 用户可以是客户(使用 CliProfile)或企业(使用 BizProfile)
  • 每张卡都链接到一个客户
  • 每张卡都包含一个[积分-业务]关联

这样:客户有一张卡,可以用同一张卡在必胜客获得 3 分,在麦当劳获得 5 分)

我正在尝试编写的请求

从功能上来说,目的是一个所有者(比如必胜客)可以看到他所有的客户(有卡的客户在必胜客有积分)

从技术上讲,我正在尝试编写一个查询来获取所有客户(即 CliProfile 查询集),其卡片(至少 1 个)的积分(至少 1 个)的所有者(只有 1 个) ) 谁的用户(只有 1 个)= request.user ?

您知道如何编写这样的查询吗?非常感谢。

最佳答案

要在 filter() 中匹配模型中的字段,您需要使用两个下划线。以下对我有用

CliProfile.objects.filter(card__points__at_owner=request.user)

但是@Alex 的建议最有意义,除非这只是您尝试做的事情的一个例子。

如果您想要与多张卡片之一相关联的配置文件,您可以使用 __in field lookup :

CliProfile.objects.filter(card__in=IterableOfCards)

此外,您不要在 filter() 中使用 == .这将返回 True 或 False,然后在 filter() 调用中有效地传递该值,从而使调用 filter(True or False) 不会做任何有用的事情。您必须使用 =,因为您将命名参数传递给过滤器函数。

为什么用 card 而不是 card_set()?cart_set 仅存在于 CliProfile 的一个实例中。您不在 CliProfile 的实例中,您正在尝试获取它们的列表。

您可以在终端中尝试,它会告诉您有效的选择。

#Note that it doesn't matter what you put after=, since it fails before that is checked.
>>> CliProfile.objects.filter(card_set=True)
FieldError: Cannot resolve keyword 'card_set' into field. Choices are: card, id, user

一个CliProfile可以被多张卡片引用,这就是为什么里面有card_set但是你想匹配一张卡片的原因。 cardpointsat_owner字段为request.user

您可以使用 a_cliprofile_instance.card_set.filter() 来获取他们卡片的子集,或者使用 a_cliprofile_instance.card_set.all() 来显示他们的所有卡片

关于Django 和编写包含大量连接的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23432071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com