[PYTHON] Implement follow functionality in Django

First stage

Django has implemented a follow function that is almost essential for SNS apps. It will be a self-implementation that does not use the library. Customize it to suit your needs and requirements.

Development environment

Specific requirements for follow function

--You can follow / unfollow --You can't follow yourself --You can check the number of followers and followers

The list of followers is omitted here. Implement the minimum required functional requirements.

Table design

There is a way to create only one table, but I personally have the impression that the SQL statement becomes redundant and it is difficult to manage the table, so I will prepare two this time.

** follow_relation table **

data Information to store Data type
user_id User ID of the follower UUID
followed_id User ID of the person being followed UUID

** follow_count table **

data Information to store data型
user_id User ID UUID
follow Number of followers INT
followed Number being followed INT

The follow_relation table manages the follow status between users, and the follow_count table manages the number of followers and followers of users.

Edit views.py

Let's implement the follow function as soon as the table is created. The general flow of the follow function is as follows.

Page request
↓
followd_Check & display follow status with status function
↓
Press the follow button
↓
The follows function processes according to the follow status
↓
Redirect to original page

Then it becomes the following code.

followed_status function


@login_required
def followed_status(request, accesskey):
    #abridgement
    #Get the parameters you need

    #Connect to database
    connection = MySQLdb.connect(
    host='localhost',
    user='***',
    passwd='***',
    db='***',
    charset="utf8"
    )  

    #Get cursor
    cursor = connection.cursor() 

    #Set of queries
    follow_relation = "SELECT COUNT(*) FROM follow_relation where user_id = UUID_TO_BIN(%s) and followed_id = UUID_TO_BIN(%s);"

    #Executing a query
    # user_id、followed_Get id by yourself
    cursor.execute(follow_relation, (user_id, followed_id))
    row_follow = cursor.fetchone()
    follows = row_follow[0]

    #Determine if the login user and page user are the same person
    #Make sure you can't follow the same person
    if followed_id == user_id:
        followed_status_code = 1
    else:
        followed_status_code = 2

    #True if follows is greater than 0
    #Returns False if follows is 0
    followed = False
    if follows > 0 :
        followed = True
 
    return followed_status_code, followed

Please pull out the required parameters from your own table. All you need this time is the ID of the follower and the follower. The side that user_id follows and the side that followed_id follows.

--Match user IDs

Assign a status code to determine if they are the same person.

If followed_status_code = 1, then yourself (cannot follow) If followed_status_code = 2, others (you can follow)

Will be.

--Check the follow status

Check the follow status with True and False.

If it's False, I haven't followed it yet If True, you are already following

Will be. Now let's look at the follows function.

follows function


@login_required
def followes(request, accesskey):
    #abridgement
    #Get the parameters you need

    #Connect to database
    connection = MySQLdb.connect(
    host='localhost',
    user='***',
    passwd='***',
    db='***',
    charset="utf8"
    )  

    #Get cursor
    cursor = connection.cursor()

    #Please set a common query
    #Get the information you need here

    #Prevent yourself from following
    if user_id == followed_id:
        followed = False
        #Save follow status to session
        request.session['page_followed_status'] = followed
    else:
        if followed == False:
            #It will be the process when following
            #Set of queries
            #Insert new follow relationship
            follow_reation = "INSERT INTO follow_relation (user_id, followed_id) values(UUID_TO_BIN(%s), UUID_TO_BIN(%s));"

            #Increase the number of followers by one
            follow_update = "UPDATE follow_count SET follow = follow + 1 where user_id=UUID_TO_BIN(%s);"  

            #Increase the number of followers of the follower user by one
            followed_update = "UPDATE follow_count SET followed = followed + 1 where user_id=UUID_TO_BIN(%s);"

            #Executing a query
            cursor.execute(follow_relation, (user_id, followed_id))

            cursor.execute(follow_update, (user_id, ))

            cursor.execute(followed_update, (followed_id, ))

            #Close the connection
            cursor.close()
            connection.commit()
            connection.close() 

            #Make it follow
            followed = True
            request.session['page_followed_status'] = followed

        else:
            #It will be the process when unfollowing
            #Set of queries
            #Delete follow relationship
            follow_relation = "DELETE FROM follow_relation where user_id=UUID_TO_BIN(%s) and followed_id = UUID_TO_BIN(%s);"

            #Reduce the number of unfollowed users by one
            follow_update = "UPDATE follow_count SET follow = follow - 1 where user_id=UUID_TO_BIN(%s);"

            #Reduce the number of followers of unfollowed page users by one
            followed_update = "UPDATE follow_count SET followed = followed - 1 where user_id=UUID_TO_BIN(%s);"

            #Executing a query
            cursor.execute(sql_followrelation_delete, (user_id, followed_id))

            cursor.execute(sql_follow_update, (user_id, ))

            cursor.execute(sql_followed_update, (followed_id, ))

            #Close the connection
            cursor.close()
            connection.commit()
            connection.close() 

            #Make it unfollowed
            followed = False
            request.session['page_followed_status'] = followed

    return redirect('Original page', accesskey)

This is the actual processing of branching with an if statement and following or unfollowing. And finally, the follow status is switched. Redirect to the original page and finish. (This time, page transition occurs because Ajax etc. are not used)

Finally, edit the view for display.

result function


@login_required
def result(request, accesskey):

    #abridgement

    #Understand the status of follow
    status = followed_status(request, accesskey)
    followed_status_code = status[0]
    followed = status[1]
    #Save follow status to session (temporary)
    request.session['page_followed_status'] = followed

    params = {
        #abridgement

        'page_followed_status': followed,
        'page_followed_status_code': followed_status_code,
    }
    return render(request, 'result.html', params)

Only the relevant parts are listed. We are checking the follow status by calling the followed_status function. (The followed_status function returns the status code and follow status.) And I save it temporarily in the session.

Editing urls.py

urls.py


urlpatterns = [
    #abridgement
    path('Original page', views.pages, name='Set by yourself'),
    path('Original page/follow/', views.follows, name="follows"),
    #abridgement
]

Edit template

Finally, the template.

result.html


            <!--Add follow button-->
            {% if page_followed_status_code is 2 %}
                {% if page_followed_status is False %}
                <p><a href="{% url 'follows' page_accesskey %}">To follow</a></p>
                {% else %}
                <p><a href="{% url 'follows' page_accesskey %}">Stop following</a></p>
                {% endif %}
            {% endif %}

It is displayed only when the status code is 2 (when it is between others, not yourself).

And if the follow status is False, it is displayed as" follow ", and when it is True, it is displayed as "stop following".

When the link is pressed, the follows function is called at the page destination, the follow process is performed, and the page is redirected to the original page.

Finally

Please modify the code and use it in your own way. You can implement the "Like feature" in much the same way!

Recommended Posts

Implement follow functionality in Django
How to implement Rails helper-like functionality in Django
Implement JWT login functionality in Django REST framework
Models in Django
Implement a Custom User Model in Django
Forms in Django
Implement Enigma in python
Implement recommendations in Python
Implement XENO in python
Model changes in Django
Implement sum in Python
Implement Traceroute in Python 3
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Implement LSTM AutoEncoder in Keras
Performance optimization in Django 3.xx
PHP var_dump in Django templates
Handle constants in Django templates
Rename table columns in Django3
Implement timer function in pygame
Implement Style Transfer in Pytorch
Implement recursive closures in Go
Output table structure in Django
Implement naive bayes in Python 3.3
Implement UnionFind (equivalent) in 10 lines
Implement ancient ciphers in python
Implement Redis Mutex in Python
Implement extension field in Python
Implement fast RPC in Python
Implement method chain in Python
(Note) Django in Vagrant environment
Implement Dijkstra's Algorithm in python
Implement Slack chatbot in Python
Create an easy-to-use follow model in Django using ManyToManyField through
Show Django ManyToManyField in Template
Implement Gaussian process in Pyro
Implement an add form button in your Django inline form set
Implementation of JWT authentication functionality in Django REST Framework using djoser
Implement stacking learning in Python [Kaggle]
reload in django shell with ipython
Implement Table Driven Test in Java
Implement R's power.prop.test function in python
Set placeholders in input fields in Django
8 Frequently Used Commands in Python Django
Dynamically add form fields in Django
Errors related to memcached in django
Implementation of login function in Django
Register your Django application in your project
Implement a date setter in Tkinter
Implement the Singleton pattern in Python
Implement a Django app on Hy
Write foreign key constraints in Django
How to reflect CSS in Django
Switch the language displayed in Django 1.9
Get parameter values ​​in Django templates
The meaning of ".object" in Django
Quickly implement REST API in Python
Deploy Django in 3 minutes using docker-compose
Pin factory_boy seed value in Django
GraphQL API with graphene_django in Django
Like button implementation in Django + Ajax
Get the query string (query string) in Django