简体   繁体   English

遍历组,然后逐项循环

[英]Iterate through groups, then loop item by item

Django 1.11.4 Django 1.11.4

PostgreSQL 9.6.3 PostgreSQL 9.6.3

Below is a bookmark model. 下面是一个书签模型。

class Bookmark(CommonUrlMethodsMixin,
               models.Model):
    memo = models.CharField(max_length=200,
                            null=False,
                            blank=True,
                            default="")  # Intentionally blank.
                                              # For displaying in ModelForm.

    content_type = models.ForeignKey(ContentType)
    content_type_for_filter = models.CharField(max_length=6,
                            null=False,
                            blank=True,
                            default="")
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE)

    def __str__(self):
        return "{}: {} {}".format(self.content_object._meta.verbose_name.title(), self.content_object, self.memo)

    class Meta:
        verbose_name = _("bookmark")

In my project bookmarked can be a Frame, an Item, a Sheet. 在我的项目中,带有书签的可以是框架,项目,工作表。 So, I organized a special field in the Bookmark model content_type_for_filter. 因此,我在书签模型content_type_for_filter中组织了一个特殊字段。 It may contain either "frame", or "item" or "sheet". 它可以包含“框架”,“项目”或“工作表”。

Bookmarks must be shown in groups: first bookmarks for Frames, then for Items and lastly for Sheets: 书签必须按组显示:首先是框架的书签,然后是项的书签,最后是图纸:

Frames
     bookmark 1
     bookmark 2
     bookmark 3
Sheets
     bookmark 4
     bookmark 5
Items
     bookmark 6
     bookmark 7
     bookmark 8

Then in the personal area I'd like to show the bookmarks. 然后,在个人区域中,我想显示书签。 In views now I have: 现在在视图中,我有:

def get_context_data(self, **kwargs):
    bookmarks = user.bookmark_set.all()
    # context['bookmarks'] = bookmarks

It seems that my code is not acceptable. 看来我的代码不可接受。 Look: I will have to handle bookmarks somehow in Python. 看:我将不得不以某种方式在Python中处理书签。 Use a named tuple or something. 使用命名的元组之类的东西。 Or at least three lists of lists. 或至少三个列表列表。

I suppose, that my select from the data base is not optimal. 我想我从数据库中选择的不是最佳的。 Is suppose, it may be possible to group by "content_type_for_filter". 假设可以按“ content_type_for_filter”分组。 Then loop through groups. 然后循环浏览组。 And then loop through the contents of the groups. 然后循环浏览组的内容。 But I don't know how. 但是我不知道如何。

Could you help me understand how to do that? 您能帮我理解该怎么做吗? Is it possible with ORM? ORM有可能吗? If not, how to do that without ORM? 如果没有,那么在没有ORM的情况下该怎么做?

My suggestion is that you further filter your bookmarks queryset and put it inside a dict or another class that better suit your needs: 我的建议是,您进一步过滤书签queryset并将其放在dict或另一个更适合您需要的类中:

bookmarks = user.bookmark_set.all()
from collections import OrderedDict as odict
groups = odict()
for group in ['Frames', 'Sheets', 'Itens']:
    groups[group] = bookmarks.filter(content_type_for_filter=group)
context['groups'] = groups

An more advanced option could be aggregating your queryset. 一个更高级的选项可能是聚合您的查询 AFAIK, it groups only values and/or annotations, but I could be wrong. AFAIK,它仅将值和/或注释分组,但是我可能是错的。

First of all, you need to define a context: 首先,您需要定义一个上下文:

 
 
 
  
  def get_context_data(self, **kwargs): context = super(<YOUR VIEW NAME>, self).get_context_data(**kwargs)
 
  

Then, it seems you didn't defined an user. 然后,似乎您没有定义用户。 You may define it as follows 您可以定义如下

 
 
 
  
  # current user context['bookmarks'] = self.request.user.bookmark_set.all() # using an user specified in kwargs user = get_object_or_404(User, kwargs.get('user_pk')) # or, if your view is a DetailView of User user = self.get_object() # then, finally context['bookmarks'] = Bookmarks.objects.filter(user=user)
 
  

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

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