본문으로 바로가기

🚀 raw_id_field

 

 

The Django admin site | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

기본적으로 장고는 FK에 위와 같은 셀렉트 박스를 제공합니다. 그러나 때때로 너무 많은 선택지가 있을 경우 드랍 다운식의 셀렉트 박스는 이용하기에 불편할 수 있습니다. raw_id_field는 FK, ManyToManyField에 대해 더 편리한 input 위젯을 제공합니다.

 

다음 어드민 패널에서 host를 raw_id_fields로 등록해보았습니다.

@admin.register(models.Room)
class RoomAdmin(admin.ModelAdmin):

    """ Room Admin Definition """

    fieldsets = (
        (
            "Basic Info",
            {"fields": ("name", "description", "country", "address", "price")}
        ),
        
        ... 중략
        (
            "Last Detail",
            {"fields": (
                "host",
            )}
        )
    )

    raw_id_fields = (
        "host",
    )

 

이제 Host에는 다음과 같이 셀렉트 박스가 아니라 돋보기를 클릭하면 User admin이 뜨는 방식으로 바뀌었습니다. 이는 host가 User 모델을 연결한 것이기 때문입니다. 

이로써 유저가 너무 많아졌을 때 필터를 적용하거나 검색하는 것도 가능해졌습니다.

    host = models.ForeignKey(
        "users.User", related_name="rooms", on_delete=models.CASCADE)

 

 

 

 

 

🚀 inline-admin

 

 

The Django admin site | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

어드민 안에 또 다른 어드민을 넣는 방법입니다. 인라인 어드민에는 두가지 종류가 있다고 합니다. 차이는 외관 밖에 없으니 마음에 드는 걸로 사용하면 됩니다.

 

Django provides two subclasses of InlineModelAdmin and they are: 

The difference between these two is merely the template used to render them.

 

 

# 만약 StackedInline을 쓰고 싶다면 admin.StackedInline으로 쓰기만 하면 됩니다.
class PhotoInline(admin.TabularInline):


    # 모델을 지정해줍니다.
    model = models.Photo


@admin.register(models.Room)
class RoomAdmin(admin.ModelAdmin):

    """ Room Admin Definition """
    
    inlines = (PhotoInline, )

    ... 중략

 

이 결과 어드민에 Photo가 추가 되었습니다. Photo 모델은 Room과 FK 관계입니다. 하나의 Room이 여러 개의 Photo를 가질 수 있으므로 다음과 같이 여러 사진을 등록할 수 있도록 여러 row가 떴습니다.

 

또, Django가 해당 Room에 속하는 Photo를 자동으로 찾아줍니다. 참 편리하죠~

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체