当用户在Django和Postgres中接受好友请求时,如何在表中保存两行?

时间:2018-06-25 17:40:11

标签: mysql json django postgresql django-rest-framework

我的好友关系表:

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端点中处理操作?

1 个答案:

答案 0 :(得分:0)

settings.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#一个=应用程序名称

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')),
]