简体   繁体   English

双向表和Django ORM

[英]Two way table and django ORM

Consider two django models 'User' and 'BoardGame', the latter has a ManyToMany field 'vote' defined with a custom through table: 考虑两个Django模型“ User”和“ BoardGame”,后者具有通过自定义穿透表定义的ManyToMany字段“ vote”:

class Vote(models.Model):
    user = models.ForeignKey(User)
    boardgame = models.ForeignKey(BoardGame)
    vote = models.IntegerField()

I need to print a two way table having users names on the top, boardgames names on the left column and votes in the middle. 我需要打印一个双向表,用户名位于顶部,棋盘游戏名称位于左列,投票位于中间。

Is there a way to obtain this using django? 有没有办法使用django来获得它? (Remember that a user might not have voted every single boardgame.) (请记住,用户可能没有对每个棋盘游戏进行投票。)

UPDATE: MORE DETAILS 更新:更多详细信息

1) Clearly this can be work out using some lines of python (which probably would result in many queries to the database), but I'm more interested in discovering if there is something directly implemented in django that could do the work. 1)显然,可以使用一些python行解决这个问题(这可能会导致对数据库的许多查询),但是我对发现django中是否有可以直接完成的工作更感兴趣。 After all a ManyToMany field is nothing but a two way table (in this case with some data associated). 毕竟ManyToMany字段不过是双向表(在这种情况下,关联了一些数据)。

2) A possible 'solution' would be a FULL OUTER JOIN using a raw query, but, again, I am looking for something built-in inside django. 2)可能的“解决方案”将是使用原始查询的FULL OUTER JOIN,但同样,我正在django中寻找内置的东西。

3) More specifically I'm using Class Based View and I was wondering if there exists an appropriate query to associate to queryset parameter of ListView. 3)更具体地说,我正在使用基于类的视图,我想知道是否存在适当的查询来关联到ListView的queryset参数。

Assuming: 假设:

class User(models.Model):
    ...

class BoardGame(models.Model):
    users = models.ManyToManyField(User, through='Vote')
    ...

class Vote(models.Model):
    user = models.ForeignKey(User)
    boardgame = models.ForeignKey(BoardGame)
    vote = models.IntegerField()

would work like this: 将像这样工作:

from django.db import connections, reset_queries
reset_queries()

users = User.objects.all().prefetch_related('vote_set')
table = []
table.append([''] + list(users))
for board_game in BoardGame.objects.all().prefetch_related('vote_set'):
    row = [board_game]
    for user in users:
        for vote in user.vote_set.all():
            if vote in board_game.vote_set.all():
                row.append(vote)
                break
        else:
            row.append('')
    table.append(row)

len(connection.queries)  # Returns always 4

This is not the solution you wanted, but it shows a way to get the table from the database with only 4 queries no matter how many objects you have. 这不是您想要的解决方案,但是它显示了一种方法,无论您有多少个对象,都仅用4个查询即可从数据库中获取表。

我认为Django核心或基于类的通用视图中没有任何东西可以为您呈现表,但请尝试django-tables2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM