python/Django
[Django] ModelAdmin 상에서 list_display 내에서 ForeignKey 필드를 불러오는 방법 (일대다 관계 2)
http://portfolio.wonpaper.net
2022. 5. 20. 15:25
A 테이블과 B 테이블이 일대다 형태로 FoeignKey로 연결된 필드가 있을때, ModelAdmin 상의 list_display 내에서 그 해당 필드들을 불러오는 방법이다.
[ models.py ]
1
2
3
4
5
6
7
|
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=255)
|
cs |
[ admin.py ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class AuthorAdmin(admin.ModelAdmin):
model = Author
list_display = ['name', 'get_book_cnt' ]
def get_book_cnt(self, obj):
return obj.book_set.count()
get_book_cnt.short_description = '' # 제목이름
admin.site.register(Author, AuthorAdmin)
class BookAdmin(admin.ModelAdmin):
model = Book
list_display = ['title', 'get_name', ]
def get_name(self, obj):
return obj.author.name
get_name.admin_order_field = 'author' # 정렬기능
get_name.short_description = 'Author Name' # 제목이름
#Filtering on side - for some reason, this works
#list_filter = ['title', 'author__name']
admin.site.register(Book, BookAdmin)
|
cs |
참고 : https://stackoverflow.com/questions/3586149/django-modeladmin-list-display