SoFunction
Updated on 2025-03-10

Django tag filtering implementation code (one-to-many, many-to-many)

Achieved goals (one to many)

Implementation of course implementation: course type, difficulty level, and whether to hide three ways

Each video file has a course type, a difficulty level, and whether it is hidden

The design database is as follows:

# Video Classification Tableclass VideoType():
 Video_Type = (max_length=50)
 class Meta:
 verbose_name_plural = 'Video Classification'
 def __str__(self):
 return self.Video_Type
# Video difficulty tableclass VideoDif():
 Video_dif = (max_length=50)
 class Meta:
 verbose_name_plural = 'Video Difficulty'
 def __str__(self):
 return self.Video_dif
# Video: ID, video picture, video name, video introduction, video address, video classification, video difficulty, weight, whether to displayclass Video():
 Video_img = (max_length=100)
 Video_title = (max_length=100)
 Video_text = ()
 Video_type_id = ('VideoType', on_delete=,)
 Video_dif_id = ('VideoDif', on_delete=,)
 Video_qz = (default=0)
 display_choice = (
 (1, 'show'),
 (2, 'hide'),
 )
 display = (verbose_name='state', choices=display_choice, default=1)
 class Meta:
 verbose_name_plural = 'video'

URL file:

from  import re_path
urlpatterns = [
 path('admin/', ),
 path('video/', ),
 # Add three fields through regular expressions to get the current selection from the foreground re_path('video-(?P<Video_type_id>(\d+))-(?P<Video_dif_id>(\d+))-(?P<display>(\d+))', ),

Background program file:

def video(request,*args,**kwargs):
 # Use the background filter database condition = {}
 # kwargs is a key-value pair obtained from the foreground URL. If accessed for the first time, an initialization is made for the dictionary. if not kwargs:
 kwargs ={
  'Video_type_id':0,
  'Video_dif_id':0,
  'display':0,
 }
 # Take out the values ​​passed from the kwargs dictionary in turn for k, v in ():
 # First change the value passed into a numeric type temp = int(v)
 kwargs[k] = temp
 # If there is a value in kwargs, the loop will assign the value to the condition list if temp:
  condition[k] = temp
 # Get a list of video types from the database VideoType_list = ()
 # Get a list of video difficulty from the database VideoDif_list = ()
 # From the video list in the database, get the content of the field that is displayed, which is in the form of a tuple: ((1, 'Show'), (2, 'Hide')) # After map, a map object is formed: {'id':1,'name':'display'} # Finally the list is converted to a list: [{'id': 1, 'name': 'show'}, {'id': 2, 'name': 'hide'}] display_list = list(map(lambda x:{'id':x[0],'name':x[1]},.display_choice))
 # Filter the video list in the database based on the condition list video_list = (**condition)
 return render(
 request,
 '',
 {
  'VideoType_list': VideoType_list,
  'VideoDif_list': VideoDif_list,
  'kwargs': kwargs,
  'video_list': video_list,
  'display_list': display_list,
 }
 )

Front desk display files:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style>
 .condition a{
  display: inline-block;;
  padding: 5px 8px;
  border: 1px solid #dddddd;
 }
 .condition {
  background-color: red;
  color: white;
 }
 </style>
</head>
<body>
 <div class="condition">
 <h1>filter</h1>
 <div>
  {% if kwargs.Video_type_id == 0%}
  <a href="/video-0-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" class="active">all</a>
  {% else %}
  <a href="/video-0-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" >all</a>
  {% endif %}
  {% for i in VideoType_list %}
  {% if  == kwargs.Video_type_id %}
   <a href="/video-{{  }}-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" class="active">{{ i.Video_Type }}</a>
  {% else %}
   <a href="/video-{{  }}-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" >{{ i.Video_Type }}</a>
  {% endif %}
  {% endfor %}
 </div>
 <div>
  {% if kwargs.Video_dif_id == 0%}
  <a href="/video-{{ kwargs.Video_type_id }}-0-{{  }}" rel="external nofollow" rel="external nofollow" class="active">all</a>
  {% else %}
  <a href="/video-{{ kwargs.Video_type_id }}-0-{{  }}" rel="external nofollow" rel="external nofollow" >all</a>
  {% endif %}
  {% for i in VideoDif_list %}
  {% if  == kwargs.Video_dif_id %}
   <a href="/video-{{ kwargs.Video_type_id }}-{{  }}-{{  }}" rel="external nofollow" rel="external nofollow" class="active">{{ i.Video_dif }}</a>
  {% else %}
   <a href="/video-{{ kwargs.Video_type_id }}-{{  }}-{{  }}" rel="external nofollow" rel="external nofollow" >{{ i.Video_dif }}</a>
  {% endif %}
  {% endfor %}
 </div>
 <div>
  {% if  == 0 %}
  <a class="active" href="/video-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}-0" rel="external nofollow" rel="external nofollow" >all</a>
  {% else %}
  <a href="/video-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}-0" rel="external nofollow" rel="external nofollow" >all</a>
  {% endif %}
  {% for item in display_list %}
  {% if  ==  %}
   <a class="active" href="/video-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" >{{  }}</a>
  {% else %}
   <a href="/video-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}-{{  }}" rel="external nofollow" rel="external nofollow" >{{  }}</a>
  {% endif %}
  {% endfor %}
 </div>
 </div>
 <div>
 <h1>result</h1>
 <div>
  {% for row in video_list %}
  <p>{{ row.Video_title }}</p>
  {% endfor %}
 </div>
 </div>
</body>
</html>

The front desk changes the active tag to realize the selected display, and controls the background filtering operation through the numbers in the a tag.

Achieved goals (many to many)

Implement the selection of three methods for course implementation: course direction, course type, and difficulty level

Each course direction contains multiple course types. After selecting the course direction, filter all course types included in the course direction.

Each video file has a course type and a difficulty level

The design database is as follows, adding a many-to-many course direction table on the one-to-many basis:

# Direction classification: ID, name (to make a many-to-many relationship with video-category)class VideoGroup():
 Video_group = (max_length=50)
 group_type = ('VideoType')
 class Meta:
 verbose_name_plural = 'Direction Classification'
 def __str__(self):
 return self.Video_group
# Video Classification Tableclass VideoType():
 Video_Type = (max_length=50)
 class Meta:
 verbose_name_plural = 'Video Classification'
 def __str__(self):
 return self.Video_Type
# Video difficulty tableclass VideoDif():
 Video_dif = (max_length=50)
 class Meta:
 verbose_name_plural = 'Video Difficulty'
 def __str__(self):
 return self.Video_dif
# Video: ID, video picture, video name, video introduction, video address, video classification, video difficulty, weight, whether to displayclass Video():
 Video_img = (max_length=100)
 Video_title = (max_length=100)
 Video_text = ()
 Video_type_id = ('VideoType', on_delete=,)
 Video_dif_id = ('VideoDif', on_delete=,)
 Video_qz = (default=0)
 display_choice = (
 (1, 'show'),
 (2, 'hide'),
 )
 display = (verbose_name='state', choices=display_choice, default=1)
 class Meta:
 verbose_name_plural = 'video'

URL file:

urlpatterns = [
 path('admin/', ),
 path('video2/', views.video2),
 re_path('video2-(?P<Video_group_id>(\d+))-(?P<Video_type_id>(\d+))-(?P<Video_dif_id>(\d+))', views.video2),
]

Background program file:

def video2(request, *args, **kwargs):
 condition = {}
 # Idea -- Construct a query dictionary """
 if:GetVideo_group_id=0 Representative direction is all,Will not affect future screening
 *List alltype
 if:Video_type_id=0
  pass
 otherwise:
  condition【'Video_type_id'】= Video_type_id
 otherwise:*List the current directiontype
 if:Video_type_id=0
  Get当前方向下的typeAllid【1,2,3,4】
  condition【'Video_type_id__in'】= 【1,2,3,4】
 otherwise:
  Need to view the current onetypeIs it in the current direction list,if在:
  condition【'Video_type_id'】= Video_type_id
  if不在:
  condition【'Video_type_id__in'】= 【1,2,3,4】
 """
 if not kwargs:
 kwargs = {
  'Video_type_id':0,
  'Video_dif_id':0,
  'Video_group_id':0,
 }
 for k, v in ():
 temp = int(v)
 kwargs[k] = temp
 # First take out the corresponding id from kwargs group_id = ('Video_group_id')
 type_id = ('Video_type_id')
 dif_id = ('Video_dif_id')
 # Remove all group lists from the database, because all directions are displayed on the page group_list = ()
 # Determine whether the group value is 0 if group_id == 0:
 # If 0, list all types VideoType_list = ()
 # If the list of type is also 0, the filter will not be used as a special operation if type_id == 0:
  pass
 # If the type list is not 0, add the type id to the filter list else:
  condition['Video_type_id'] = type_id
 # If the group value is not 0 else:
 # First, filter out the contents in the classification table based on the group's id to form an object group_obj = (id=group_id).first()
 # Then, filter out the list of all types based on the objects selected by the group, and wait for return to the foreground to use VideoType_list = group_obj.group_type.all()
 # Get the id value of the filtered type and get an object of QuerySet [(1,),(3,),(4,)] vlist = group_obj.group_type.all().values_list('id')
 # If the filtered type value is empty, it means that the corresponding type type is not found if not vlist:
  # Set an empty list  type_ids = []
 # If the filtered type value has content else:
  # Use a zip vlist to get a zip object, then convert it into a list to get a [(1,3,4)], take the first value to get (1,3,4)  type_ids = list(zip(*vlist))[0] # (1,3,4)
 #Judge if the type sent from the front desk is 0 if type_id == 0:
  # When filtering in the background, query the type_ids filtered according to the direction to query  # __in refers to querying multiple ids using a list  condition['Video_type_id__in'] = type_ids
 # If the type sent from the front desk is not 0, there are two situations else:
  # If the type value transmitted from the foreground is within the value range of the background filter  if type_id in type_ids:
  # The typeid of the background filter is filtered according to the type value transmitted from the front desk, that is, the front desk has selected a course. If the course direction changes, the course type is still within the selection range and the front desk is still selected, so we will still return the selected course type filtered content.  condition['Video_type_id'] = type_id
  # If the type value transmitted from the front desk is not within the value range of the background filter  else:
  # Filter all types of types downwards according to the course direction of the background filter  condition['Video_type_id__in'] = type_ids
  kwargs['Video_type_id'] = 0
 # The difficulty has no relationship with the many-to-many above, and it is the same as in the one-to-many situation. if dif_id == 0:
 pass
 else:
 condition['Video_dif_id'] = dif_id
 VideoDif_list = ()
 # Finally filter out the videos that meet the criteria video_list = (**condition)
 return render(
 request,
 '',
 {
  'group_list': group_list,
  'VideoType_list': VideoType_list,
  'VideoDif_list': VideoDif_list,
  'video_list': video_list,
  'kwargs': kwargs
 }
 )

Front desk display files:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
 &lt;meta charset="UTF-8"&gt;
 &lt;title&gt;Title&lt;/title&gt;
 &lt;style&gt;
 .condition a{
  display: inline-block;;
  padding: 5px 8px;
  border: 1px solid #dddddd;
 }
 .condition {
  background-color: red;
  color: white;
 }
 &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
 &lt;div class="condition"&gt;
 &lt;h1&gt;filter&lt;/h1&gt;
 &lt;div&gt;
  {% if kwargs.Video_group_id == 0%}
  &lt;a href="/video2-0-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" class="active"&gt;all&lt;/a&gt;
  {% else %}
  &lt;a href="/video2-0-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;all&lt;/a&gt;
  {% endif %}
  {% for item in group_list %}
  {% if  == kwargs.Video_group_id %}
   &lt;a class="active" href="/video2-{{  }}-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_group }}&lt;/a&gt;
  {% else %}
   &lt;a href="/video2-{{  }}-{{ kwargs.Video_type_id }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_group }}&lt;/a&gt;
  {% endif %}
  {% endfor %}
 &lt;/div&gt;
 &lt;div&gt;
  {% if kwargs.Video_type_id == 0%}
  &lt;a href="/video2-{{ kwargs.Video_group_id }}-0-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" class="active"&gt;all&lt;/a&gt;
  {% else %}
  &lt;a href="/video2-{{ kwargs.Video_group_id }}-0-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;all&lt;/a&gt;
  {% endif %}
  {% for item in VideoType_list %}
  {% if  == kwargs.Video_type_id %}
   &lt;a class="active" href="/video2-{{ kwargs.Video_group_id }}-{{  }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_Type }}&lt;/a&gt;
  {% else %}
   &lt;a href="/video2-{{ kwargs.Video_group_id }}-{{  }}-{{ kwargs.Video_dif_id }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_Type }}&lt;/a&gt;
  {% endif %}
  {% endfor %}
 &lt;/div&gt;
 &lt;div&gt;
  {% if kwargs.Video_dif_id == 0%}
  &lt;a href="/video2-{{ kwargs.Video_group_id }}-{{ kwargs.Video_type_id }}-0" rel="external nofollow" rel="external nofollow" class="active"&gt;all&lt;/a&gt;
  {% else %}
  &lt;a href="/video2-{{ kwargs.Video_group_id }}-{{ kwargs.Video_type_id }}-0" rel="external nofollow" rel="external nofollow" &gt;all&lt;/a&gt;
  {% endif %}
  {% for item in VideoDif_list %}
  {% if  == kwargs.Video_dif_id %}
   &lt;a class="active" href="/video2-{{ kwargs.Video_group_id }}-{{ kwargs.Video_type_id }}-{{  }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_dif }}&lt;/a&gt;
  {% else %}
   &lt;a href="/video2-{{ kwargs.Video_group_id }}-{{ kwargs.Video_type_id }}-{{  }}" rel="external nofollow" rel="external nofollow" &gt;{{ item.Video_dif }}&lt;/a&gt;
  {% endif %}
  {% endfor %}
 &lt;/div&gt;
 &lt;/div&gt;
 &lt;div&gt;
 &lt;h1&gt;result&lt;/h1&gt;
 &lt;div&gt;
  {% for item in video_list %}
  &lt;p&gt;{{ item.Video_title }}&lt;/p&gt;
  {% endfor %}
 &lt;/div&gt;
 &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

Summarize

The above is the implementation code of Django tag filtering introduced to you (one-to-many, many-to-many). I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!