我很努力地找到一種方法在Django/Rest Framework中的兩個模型之間創建任意關係。Django Rest Framework任意關係字段
考慮與一個主鍵,通過某些用戶或用戶組登錄許可動作存在一個表,該表是這樣的:
驗證: pk | user | action
而且pk
是自動產生的,整數。
我需要創建一個序列化器或非管理模型,它可以正確地檢索關係信息,就好像它在這個表中有一個外鍵。
總的想法是,像這樣的路線:
/customauth/test/
將產生所有的用戶被授權做的事情。請記住,在視圖中創建一個自定義屬性並使用自定義查詢集填充它並不能解決問題,因爲我使用的是JSON-API,它專門報告關係如此的東西(因此該字段必須實際上是一個相關字段或子類)。
基本上,我需要做一個相關的領域(無論是序列化或模型),行爲像一個完全自定義的數據集。我提供基於查詢集的關係,或手動指出哪些字段是「相關的」。
這裏是一個樣本所需的響應:
{
"data":{
"type":"CustomUserAuthDetailView",
"id":"test",
"attributes":{
"user":"test"
},
"links":{
"self":"http://127.0.0.1:8000/auth/test/"
}
},
"relationships":{
"auth":{
"links":{
"self":"/customauth/test/relationships/auth"
},
"data":{
"type":"auth",
"id":"1"
}
}
}
}
的JSON API plugin Django的REST框架使得對於我這種反應不過來,關係(一個或多個)必須存在,因爲我不能使用真實關係('customauth'是一個非託管表,實際上表示類似Active Directory的內容,我無法觸及,並且可能具有無限的不同值),並且Auth
表本身在user
上不是唯一的be),並且這些信息需要被其他表格所消耗,所以我不能使用content-type
和GenericForeignKey
系統。 (內容類型可以讓你有多個外部關係,但不是每行,只是每列......除非我誤解它)。
我覺得我必須要失去一些東西,因爲我不能成爲唯一想要完成這件事的人。我考慮製作自己的相關領域子類,但迄今沒有運氣,而當我沿着這條路走下去的時候,我想我會檢查是否有比我更有經驗的人知道我錯過的東西。
完整樣本應用程序:
models.py:
from django.db import models
class Auth(models.Model):
actions = (("POST", "Create"),
("GET", "Retrieve"),
("PUT", "Update"),
("DELETE", "Remove"))
user = models.CharField(max_length=24)
action = models.CharField(max_length=8, choices=actions)
class CustomUserAuth(models.Model):
class Meta:
managed = False
user = models.CharField(max_length=24, primary_key=True)
serializers.py:
from rest_framework_json_api import serializers
from .models import Auth, CustomUserAuth
class AuthSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Auth
read_only_fields = ('url',)
class CustomUserAuthSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CustomUserAuth
fields = ('user', 'url')
views.py:
from rest_framework import views
from .models import CustomUserAuth
from .serializers import CustomUserAuthSerializer
from rest_framework.response import Response
class CustomUserAuthDetailView(views.APIView):
@staticmethod
def get(request, pk, format=None):
auth = CustomUserAuth()
auth.user = pk
serialized = CustomUserAuthSerializer(
auth,
context={"request": request}
)
return Response(serialized.data)
urls.py:
from django.conf.urls import url
from django.contrib import admin
from fake_relationship.views import CustomUserAuthDetailView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^auth/(?P<pk>[\w-]+)/$',
CustomUserAuthDetailView.as_view(),
name='customuserauth-detail'
)
]
settings.py:
"""
Django settings for djtest project.
Generated by 'django-admin startproject' using Django 1.10.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/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/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '[email protected]&3)=$3v2wfq+hzg4fihrla+5()dnxdwka35^[email protected]!b17&'
# 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',
'fake_relationship'
]
REST_FRAMEWORK = {
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS':
'rest_framework_json_api.pagination.PageNumberPagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_json_api.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
}
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 = 'djtest.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 = 'djtest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/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/1.10/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/1.10/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/1.10/howto/static-files/
STATIC_URL = '/static/'
你可以在關係中使用外鍵嗎? – marin
不,CustomUserAuth表實際上並不存在,所以沒有任何東西可以擁有外鍵,Auth表的主鍵是一個自動遞增整數 - 「user」不是唯一的,也不是。由於這些原因,沒有外鍵關係是可能的。 – Keozon