SoFunction
Updated on 2024-11-18

Django Foreign Key Usage Details

I. Description

In the use of django to do web development we will encounter a problem is that we have created a number of data tables, but the contents of multiple data tables are not the same, but there is a link between for example:

I have two tables, one is to record the content of the song information, one is the content of the song operation (downloads views), if I have a downloads in the views of the number of downloads to a sort, but I can not just show the number of downloads, I need the content of the song title, at this time, we need a foreign key to do this work.

Number of times the song is operated

Song Information

II. Settlements

As in django are using files to manage the database, and then by performing connection operations, and finally used to map to the website

  dynamic_id = ('serial_num', primary_key=True)
   song = (Song, on_delete=, verbose_name='song name')
   dynamic_plays = ('plays_num')
   dynamic_search = ('search_num')
   dynamic_down = ('down_num')

You can finish setting up the foreign key, and the first parameter is the class name, so that it is associated with the song information.

# hot search songs
  search_song = .select_related('song').order_by('dynamic_search').all()[:8]
  # sort songs
  label_list = ()
  # hot songs
  play_hot_song = .select_related('song').order_by('dynamic_plays').all()[:10]
  # recommend songs
  daily_recommendation = .order_by('song_release').all()[:3]
  # hot search and download
  search_ranking = search_song[:6]
  down_ranking = .select_related('song').order_by('dynamic_down').all()[:6]
  all_ranking = [search_ranking, down_ranking]
  return render(request, 'index/', locals())

Based on the information above you can see that the field dynamic_search is utilized in search_song to link the content of the information we encountered, concatenating the information from dynamic_search and song together the external field is song, or it could be any other connection.

<img src="{% static 'image/' %}">
<br/>
{% for play_hot in play_hot_song %}
{{ play_hot.song.song_name }}
<br/>
{% endfor %}

In the .html file we use the object in to reference the information in song, play_hot_song is the field name in, the traversal is play_hot.song.song_name, play_hot is the traversal parameter, song is the field name of the interface, song_name is the content of the external object. This maps the information to the website.

III. Results

This is the whole content of this article.