私は、Django/Rest Frameworkの2つのモデル間の任意の関係を作成する方法を見つけるのに苦労しています。Django Rest Framework任意の関係フィールド
一部のユーザーまたはグループごとに許容アクションをログに記録し、主キー、で存在するテーブルを考えてみて、表は次のようになります。
認証: pk | user | action
そしてpk
が自動生成され整数。
このテーブルに外部キーがあるかのように、関係情報を正しく取得するシリアライザまたは非管理モデルを作成する必要があります。
/customauth/test/
ユーザーが行うことを許可されているすべてのものを生成します:
一般的な考え方は、このようなルートがあることです。カスタムの属性を作成してビュー内にカスタムクエリセットを設定するだけでは、JSON-APIを使用しているので、問題は解決しないことに注意してください。 RelatedFieldまたはサブクラス)。
基本的に、完全なカスタムデータセットのように動作する関連フィールド(シリアライザまたはモデルのいずれか)を作成する必要があります。クエリーセットに基づいて関係を提供するか、手動で「関連する」フィールドを手動で指定します。ここで
はサンプル所望の応答です:
{
"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"
}
}
}
}
Djangoの残りFramework用JSON API pluginは私にとって、このレスポンスをレンダリングし、しかし、関係(複数可)が存在しなければならない、と私は本物を使用することはできませんので、 (「customauth」は管理されていないテーブルですが、実際には触れられず、無制限の異なる値を持つ可能性のあるActive Directoryのようなものを表しています)Auth
テーブル自体はuser
では一意ではありませんこの情報は他のテーブルでも同じように消費される必要があるため、content-type
とGenericForeignKey
システムを使用することはできません。 (コンテンツタイプを使用すると、複数の外部関係を持つことができますが、行ごとではなく、列ごとに...)私はそれを誤解しています。
これを達成したい唯一の人にはなり得ないので、私は何かが欠けているように感じます。私はRelatedFieldの自分のサブクラスを作ることを考えましたが、今まで運がなかったので、私がその道を歩いている間、私は何かが分からないことが分かっていたかどうかを確かめてみました。
完全なサンプルアプリケーション:
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/'
Foreign Keyを関係で使用できますか? – marin
いいえ、CustomUserAuthテーブルは実際に存在しないため、外部キーを持つことはできません。また、Authテーブルのプライマリキーは自動インクリメント整数です。 'user'は一意ではありません。これらの理由により、外部キーの関係は可能ではありません。 – Keozon