중첩 외래 키 할당: 단순화된 접근 방식
질문
Django REST Framework의 모델 직렬 변환기는 ID 정수 게시를 허용하여 외래 키 관계를 처리합니다. 할당 목적으로. 그러나 이 동작을 중첩된 직렬 변환기로 확장하면 특히 기존 데이터베이스 개체만 할당할 때 문제가 발생합니다.
가장 간단한 중첩 솔루션
기본 지원이 없는 경우 다음을 수행할 수 있습니다. 중첩된 하위 데이터를 포함하도록 상위 직렬 변환기의 to_representation()을 재정의합니다.
class ParentSerializer(ModelSerializer): def to_representation(self, instance): response = super().to_representation(instance) response['child'] = ChildSerializer(instance.child).data return response
이 접근 방식은 간단하고 효과적인 솔루션을 제공합니다. 중첩된 하위 항목이 있는 상위 인스턴스를 생성하고 읽는 데 사용됩니다.
일반 접근 방식
보다 일반화된 처리를 위해 사용자 정의 직렬 변환기 필드를 활용할 수 있습니다.
class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField): def __init__(self, **kwargs): ... def use_pk_only_optimization(self): ... def to_representation(self, instance): ...
이를 정의하여 필드를 상위 직렬 변환기에 추가하고 직렬 변환기를 하위 직렬 변환기 클래스로 설정하면 단일 키를 사용하여 외래 키 할당을 수행할 수 있습니다. key:
class ParentSerializer(ModelSerializer): child = RelatedFieldAlternative(queryset=Child.objects.all(), serializer=ChildSerializer)
이 일반 방법의 장점은 이 동작을 요구하는 여러 직렬 변환기에 적용할 수 있어 각각에 대한 사용자 정의 필드 및 방법의 필요성이 줄어든다는 것입니다.
위 내용은 Django REST 프레임워크에서 중첩된 외래 키를 할당하는 방법: 단순화된 접근 방식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기