특정 사례에 대한 Django 모델 저장 재정의
Django에서 모델의 save() 메서드는 데이터를 데이터베이스에 유지하는 역할을 합니다. 그러나 특정 기준에 따라 이 동작을 수정해야 하는 시나리오가 있습니다. 그러한 사례 중 하나는 이미지가 새로 추가되거나 업데이트될 때만 이미지 크기를 조정하는 것입니다.
문제:
이미지, 썸네일 및 설명 필드가 있는 모델에서 메인 이미지(이미지)를 생성하거나 수정하는 경우에만 썸네일(thumb)의 크기를 조정하여 저장해야 합니다. 설명 필드를 업데이트해도 이미지 크기 조정이 실행되어서는 안 됩니다.
해결책:
이를 달성하려면 확인하는 사용자 정의 속성을 사용하여 기본 save() 메서드를 재정의할 수 있습니다. 이미지 필드의 변경 사항:
<code class="python">class Model(model.Model): _image = models.ImageField(upload_to='folder') thumb = models.ImageField(upload_to='folder') description = models.CharField() def set_image(self, val): self._image = val self._image_changed = True def get_image(self): return self._image image = property(get_image, set_image) def save(self, *args, **kwargs): if getattr(self, '_image_changed', True): small = rescale_image(self.image, width=100, height=100) self.thumb = SimpleUploadedFile(name, small_pic) super(Model, self).save(*args, **kwargs)</code>
작동 방식:
- set_image() 메서드는 _image 필드를 업데이트하고 _image_changed 플래그를 다음으로 설정합니다. 사실입니다.
- get_image() 메서드는 _image 필드의 현재 값을 반환합니다.
- image 속성은 set_image() 및 get_image() 메서드를 모두 래핑하여 일관된 인터페이스를 제공합니다.
- 재정의된 save() 메서드에서는 _image_changed 플래그가 확인됩니다. True이면 이미지가 변경되거나 추가되었음을 의미합니다.
- 이 경우 썸네일의 크기가 조정됩니다.
- super() 메소드가 호출되어 모델을 데이터베이스에 저장합니다. 크기가 조정된 썸네일(필요한 경우) 및 업데이트된 설명.
위 내용은 이미지 크기 조정을 위해 Django 모델 저장을 재정의하는 경우의 상세 내용입니다. 자세한 내용은 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 Linux 새 버전
SublimeText3 Linux 최신 버전

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

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

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.