Tol*_*ola 2 django foreign-keys django-models django-admin
I want to make a music library app and in the admin/artist page I would like to link to a list with all the albums by the artist.
Models look like this:
class Artist(models.Model):
artistName = models.CharField(max_length=100, blank = False)
genre = models.CharField(max_length=100, blank = False)
def __str__(self):
return self.artistName
class Album(models.Model):
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
albumName = models.CharField(max_length=500, blank = False)
year = models.IntegerField(blank = False)
def __str__(self):
return self.albumName
Run Code Online (Sandbox Code Playgroud)
Now for the admin part, I imagine that I make an ArtistAdmin model and then somehow use list_display to link to a filtered version of the Album model. Can anyone tell me how to do this or suggest a better way of doing it?
我有完全相同的需求;这是迄今为止我提出的最简单的方法。
管理员列表有list_filter,例如,您可以使用它来执行此操作(假设您注册了管理类等):
class AlbumAdmin(admin.ModelAdmin):
list_display = ('artist', 'albumName', 'year',)
list_filter = ('artist',)
Run Code Online (Sandbox Code Playgroud)
这将在您的管理站点中添加一个带有艺术家列表的右列,如果您单击其中一个,专辑列表将被过滤以仅显示由该艺术家制作的那些。
有了这个,这就是诀窍,即使你没有声明“list_filter”,Django 仍然会根据 URL 参数过滤内容。所以,我激活了过滤器,我点击了我的一个“艺术家”,所以列表被过滤了,我可以看到它如何格式化 URL,类似于 […]/admin/app_name/model_name/?foreignKeyName__id__exact=XX
在你的情况下,我想它看起来类似于:[…]/admin/music_library/album/?artist__id__exact=XX
尝试按照这些步骤操作,然后删除“list_filter”行,您将看到该 URL 仍然有效。
所以现在我们知道我们唯一需要的是传递参数artist__id__exact=XX,所以我们必须为此附加一个带有按钮的列。
class ArtistAdmin(admin.ModelAdmin):
list_display = ('artistName', 'genre', 'artists_list_field')
def artists_list_field(self, obj):
base_url = reverse('admin:music_library_album_changelist')
return mark_safe(u'<a href="%s?artist_id__exact=%d">Albums</a>' % (
base_url, obj.id))
Run Code Online (Sandbox Code Playgroud)
有了这个,你就可以工作了。我希望它有用!
归档时间: |
|
查看次数: |
947 次 |
最近记录: |