Complex query in Django -


Maybe there is a simple question, but after a few years of php experience I started working with Django: - )

Problem: We have a pair of models - "Categories" and "Posts". "Categories" has set up a post-series tree, "Post" is a plain list of blog posts with fields of foreigners related to category models. Here's an example:

  Category categories (ns_node): title = model.ccarfield (max_long = 150) slug = model. Slufffield (Exclusive = True) Class Post (model.model): Title = Model Serifield (Max_Lange = 150) Slug = Model Slufffield (Exclusive = True) Text = Model Textfield () category = model FERNKEY (categorias)  

NS_Node - Class library with PĂ©rebere, enforces nested set data model.

The user can view the post by looking at the page with the URL '/ books / sci-fi /' for a specific category. In the category "Categories" we just have to select the posts associated with the 'SIS-Fi' category. Now I am doing it like this:

  def category (request, path): # 'path' is books / science-fi ', ​​locates current category code from url class Category_slug = path Divide ('/') [- 1] # Get the current category object range = categories.Bejects (slug = category_slog) # Get hair in the hair classes = category. Get_descendants (); # List the IDs for the required categoriesEidS = [child.id for the child in the child] #Current Category ID ID Append (category.id) # Select the posts for existing and nested categories posts_list = Post.objects.filter (category__in = id)  

This works, but the internal voice is called That there are some unnecessary steps in this code. Can you recommend this code to make it more simple and valid? Thank you.

You can do some customization.

First, the in filters accepts objects and IDs, so that you can skip the understanding of the list:

  categories = list ( Category.app_descendants) categories.append (post) .objects.filter (category__in = categories)  

For further improvement, you should be dirty with the implementation of nested sets. I am not fully aware of this, but seeing the tree-beer documentation, it looks like MPT, which I understand. If so, then we can rely on the fact that in the categories we want, there is a lft attribute with value of lft and rgt To complete one thing in the current category:

  Post.objects.filter (category__lft__range = (category.lft, category.rgt))  

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -