显示图像的专辑标题 - 外键

时间:2014-05-12 05:18:19

标签: python django

我正在尝试在管理界面中显示与我的图像相关的相册标题

class Album(models.Model):
    title = models.CharField(max_length = 60)

    def __unicode__(self):
        return self.title

class Tag(models.Model):
    tag = models.CharField(max_length = 50)

    def __unicode__(self):
        return self.tag

class Image(models.Model):
    title = models.CharField(max_length = 60, blank = True, null = True)
    image = models.FileField(upload_to = get_upload_file_name)
    tags = models.ManyToManyField(Tag, blank = True)
    albums = models.ForeignKey('Album')
    width = models.IntegerField(blank = True, null = True)
    height = models.IntegerField(blank = True, null = True)
    created = models.DateTimeField(auto_now_add=True)

我如何获得这些专辑标题是用这种方法

def albums_(self):
    lst = [x[1] for x in self.albums.values_list('albums')]
    return ", ".join(lst)

然而它无法正常工作。我不知道如何解决这个问题。如何将相册标题显示到适当的图像?

class ImageAdmin(admin.ModelAdmin):
    search_fields = ["title"]
    list_display = ["__unicode__", "title", "tags_", "albums_", "created"]
    list_filter = ["tags", "albums"]

admin.site.register(Image, ImageAdmin)

1 个答案:

答案 0 :(得分:1)

首先,摆脱albums_()。该方法在其当前实现中几乎没有任何意义。然后相应地更改ImageAdmin:

class ImageAdmin(admin.ModelAdmin):
    search_fields = ["title"]
    # Don't call albums_().  Aside from the fact that it doesn't do what you want it to do,   
    # The functionality you're looking for is already provided by Django:
    list_display = ["title", "tags_", "albums", "created"] 
    list_filter = ["tags", "albums"]

当您按照自己的方式创建外键时,只会有1张与该图像相关的相册。从您问题中的措辞来看,似乎您要么将外键字段放在相册中,要么您想要一个ManyToMany字段