检索一组间接相关的模型对象

发布于 2024-10-14 04:51:26 字数 1131 浏览 3 评论 0 原文

我有 4 个模型:

class TransitLine(models.Model):
    name = models.CharField(max_length=32)

class Stop(models.Model):
    line = models.ForeignKey(TransitLine, related_name='stops')

class ExitType(models.Model):
    name = models.CharField(max_length=32)
    people_limit = models.PositiveSmallIntegerField()

class Exits(models.Model):
    TOKEN_BOOTH     = 0
    GATE            = 1
    REVOLVING_DOOR  = 2

    EXIT_TYPES = (
        (TOKEN_BOOTH, 'Token booth'),
        (GATE, 'Gate'),
        (REVOLVING_DOOR, 'Revolving door'),
    )
    name = models.CharField(max_length=32)
    stop = models.ForeignKey(Stop, related_name='exits')
    type = models.ForeignKey(ExitType, related_name='exits')

我有一个 TransitLine 对象。我想检索与 TransitLineStop 对象相关的所有唯一的 ExitType 对象(真是满嘴的)。

我想要做的一些半伪代码:

tl = TransitLine.objects.get(id=1)
exit_types = []
for s in tl.stops:
    exit_types.append([e.type for e in s.exits])
unique_exit_types = list(set(exit_types))

显然,更喜欢在一次 QuerySet 调用中完成此操作。有什么建议吗?

I have 4 models:

class TransitLine(models.Model):
    name = models.CharField(max_length=32)

class Stop(models.Model):
    line = models.ForeignKey(TransitLine, related_name='stops')

class ExitType(models.Model):
    name = models.CharField(max_length=32)
    people_limit = models.PositiveSmallIntegerField()

class Exits(models.Model):
    TOKEN_BOOTH     = 0
    GATE            = 1
    REVOLVING_DOOR  = 2

    EXIT_TYPES = (
        (TOKEN_BOOTH, 'Token booth'),
        (GATE, 'Gate'),
        (REVOLVING_DOOR, 'Revolving door'),
    )
    name = models.CharField(max_length=32)
    stop = models.ForeignKey(Stop, related_name='exits')
    type = models.ForeignKey(ExitType, related_name='exits')

I have one TransitLine object. I want to retrieve all the unique ExitType objects that are related to the Stop objects of the TransitLine (that was a mouth full).

Some semi-pseudo code of what I want to do:

tl = TransitLine.objects.get(id=1)
exit_types = []
for s in tl.stops:
    exit_types.append([e.type for e in s.exits])
unique_exit_types = list(set(exit_types))

Obviously, prefer to do this in one QuerySet call. Any suggestions?

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

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

发布评论

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

评论(1

提笔落墨 2024-10-21 04:51:26

我会尝试这样的事情:

ExitType.objects.filter(exits__stop__line=line).distinct()

I would try something like this:

ExitType.objects.filter(exits__stop__line=line).distinct()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文