Django에 객체가 존재하는지 확인

Salman Mehmood 2024년2월15일
Django에 객체가 존재하는지 확인

일반적인 문제에 대한 설명에서는 모델에 객체가 존재하는지 확인하는 방법과 예외를 처리하여 사용자에게 편리한 오류를 표시하는 방법도 알아봅니다.

exists() 메서드를 사용하여 Django의 모델에 객체가 존재하는지 확인

예를 들어 Audio_store라는 모델이 있습니다. 이 클래스에는 FileField가 포함된 레코드 필드가 있습니다.

class Audio_store(models.Model):
    record = models.FileField(upload_to="documents/")

    class Meta:
        db_tables = "Audia_store"

이제 어떤 값이 존재하는지 여부를 확인해야 합니다. Django에는 객체가 존재하는지 여부를 확인하는 내장 함수가 있습니다.

exists() 함수는 다양한 상황에서 사용할 수 있지만 if 조건과 함께 사용합니다.

views.py 파일에 Audio_get 함수가 있고 이 함수에서 조건이 True 또는 False인 경우 HTTP 응답을 반환한다고 가정합니다. 작동하는지 아닌지 봅시다.

def Audio_get(request):
    vt = Audio_store.objects.all()
    if vt.exists():
        return HttpResponse("object found")
    else:
        return HttpResponse("object not found")

서버를 실행하기 전에 urls.py 파일에 URL을 추가했는지 확인해야 합니다. URL에 도달하면 views.py 파일에서 정의된 함수를 가져오고 이 경우에는 Audio_get 함수를 정의했습니다.

URL Python 코드

서버를 실행하고 브라우저를 열고 Django 서버가 실행 중인 localhost로 이동해 보겠습니다.

브라우저 열기

오류가 발생하지 않았음을 알 수 있으며 HTTP 응답을 받았습니다.

동적 URL에서 누락된 객체를 처리하기 위해 get_object_or_404 클래스를 사용할 수 있습니다. 존재하지 않는 개체를 사용하려고 하면 사용자에게 친숙하지 않은 예외가 표시됩니다.

기본 제공 Django 예외 대신 사용자(페이지를 찾을 수 없음) 오류를 표시할 수 있습니다. 유효한 오류입니다. 이 오류를 사용하기 위해 Django 서버가 개체를 찾지 못한 경우 오류를 발생시키는 예제 코드를 가져왔습니다.

from .models import Product
from django.shortcuts import render, get_object_or_404


def dynamic_loockup_view(request, id):
    # raise an exception "page not found"
    obj = get_object_or_404(Product, id=id)
    OUR_CONTEXT = {"object": obj}
    return render(request, "products/product_detail.html", OUR_CONTEXT)

404 페이지 오류가 발생합니다.

페이지를 찾을 수 없음 오류

이를 수행하는 또 다른 방법은 try 블록 안에 넣는 것입니다. 이 get_object_or_404 클래스와 같은 404 페이지를 발생시키는 Http404 클래스를 가져와야 합니다.

from django.http import Http404
from django.shortcuts import render


def dynamic_loockup_view(request, id):
    try:
        obj = Product.objects.get(id=id)
    except Product.DoesNotExist:
        # raise an exception "page not found"
        raise Http404
    OUR_CONTEXT = {"object": obj}
    return render(request, "products/product_detail.html", OUR_CONTEXT)

또한 제품 또는 모델 개체가 존재하지 않는 경우 Http404를 사용하여 404 페이지를 발생시킵니다.

Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn

관련 문장 - Django Object