首页 > 解决方案 > 当用户在 Django 和 Postgres 中接受好友请求时,如何将两行保存到表中?

问题描述

我的朋友关系表:

user_id    =   models. Foreign Key   (User,on_delete=models.CASCADE)
friend_id  =   models .Foreign Key   (User,on_delete=models.CASCADE)
created_on =   models .Date Time Field(auto_now_add=True,auto_now=False)

我想通过交替存储用户和朋友的 id 两次。

例子

用户 1 向用户 2 发送请求,他接受。

1  -->  2

所以现在数据库应该存储:

user_id friend_id  created
    1        2     (some date)
    2        1     (same date as above)

如何使用 Django-rest-framework 实现它,以便在朋友接受请求时处理单个 API 端点中的操作?

标签: mysqljsondjangopostgresqldjango-rest-framework

解决方案


设置.py

"""
Django settings for trd project.

Generated by 'django-admin startproject' using Django 2.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%buw1#8&4i=+f5@s)js1&i(a8g9#945%(5!88e!!q6)1!=n&p$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'one',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'trd.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'trd.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

one/urls.py #one 是应用的名称

from django.conf.urls import url
from rest_framework import routers

from . import views

router = routers.DefaultRouter()

urlpatterns = [
    url(r'users/(?P<user_id>\d+)/befriended/(?P<friend_id>\d+)', views.BefriendingView.as_view(), name='messages-by-user'),
]

urlpatterns += router.urls

one/Views.py #one 是应用的名称

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import MyUser

# Create your views here.
class BefriendingView(APIView):
    def get(self, request, *args, **kwargs):
        print(args)
        print(kwargs)
        # got to http://localhost:8000/api/users/1/befriended/2
        #{'user_id': '1', 'friend_id': '2'}
        # option one
        MyUser.objects.create(user_id=kwargs['user_id'], friend_id=kwargs['friend_id'])
        MyUser.objects.create(user_id=kwargs['friend_id'], friend_id=kwargs['user_id'])
        #With two lines above you will achieve this:
        #  Example: User 1 sends request to User 2 and he accepts it. 
        # 1 --> 2 So now the database should store: user_id friend_id created 1 2 (some date) 
        # 2 1 (same date as above)





        # if you need a situation where the user sends the request, database stores it, then a friend responds,
        # then database stores it,
        # go only with this line
        # MyUser.objects.create(user_id=kwargs['user_id'], friend_id=kwargs['friend_id'])
        # and in the   http://localhost:8000/api/users/1/befriended/2 
        # replace 1 and 2 with
        #  http://localhost:8000/api/users/{id_of_a_friend}/befriended/{id_of_user}
        return Response('it worked')

one/models.py # one = 应用名称

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class MyUser(models.Model):
    user_id    =   models.ForeignKey(User,on_delete=models.CASCADE, related_name="current_user")
    friend_id  =   models.ForeignKey(User,on_delete=models.CASCADE, related_name="user_friend")
    created_on =   models.DateTimeField(auto_now_add=True,auto_now=False)

source/urls source = settings.py 所在的同一文件夹

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('one.urls')),
    url(r'^api-auth/', include('rest_framework.urls')),
]

推荐阅读