2

我有一个模型定义如下:

class Artist(models.Model):
    """Model class to record Artist"""
    artist_name = models.CharField(max_length=200)
    artist_id = models.CharField(unique=True, max_length=50)
    # similar relationship is defined.
    related_to = models.ManyToManyField("self", null=True, blank=True)

    def __unicode__(self):
        return self.artist_name

当我对 django 管理面板中的艺术家使用“删除”管理操作时,我得到:

Artist: trojan

    From_artist-to_artist relationship: Artist_related_to object
    From_artist-to_artist relationship: Artist_related_to object
    From_artist-to_artist relationship: Artist_related_to object
    From_artist-to_artist relationship: Artist_related_to object

Artist: betty

    From_artist-to_artist relationship: Artist_related_to object
    From_artist-to_artist relationship: Artist_related_to object

我如何获得在删除期间被警告的实际关系?

换句话说,如何将“Artist_related_to object”人性化以反映实际的艺术家姓名。

4

2 回答 2

2

您在管理员删除问题中看到的是 Django 透明地为您创建的 ManyToMany 桥接模型的实例。

如果要更改它们的__unicode__表示,则必须定义自己的桥模型并设置ManyToManyField以将其与through 参数一起使用。

例子:

class ArtistRelationship(models.Model):
    from_artist = models.ForeignKey('Artist')
    to_artist = models.ForeignKey('Artist')

    def __unicode__(self):
        return u"%s - %s" % (self.from_artist.name, self.to_artist.name)


class Artist(models.Model):
    name = models.CharField(max_length=200)
    # ... more fields ...
    related_to = models.ManyToManyField("self", null=True, blank=True,
                                        through=ArtistRelationship)
于 2013-05-02T13:22:10.020 回答
-2

返回必须是字符串而不是 CharField,试试这个:return u"%s" % (self.artist_name, )

于 2013-05-02T09:00:59.697 回答