[英]Django multiple Foreign Key - Display related field in details admin page for add/edit
我有一个轮询应用程序,其中一个模型“ Choice”由链接到“ Person”模型的2个外键字段组成。
一旦选择了人的“姓名”,我想自动填充相关的“ photo_other”字段(带有图像链接)。 “名称”也是与Choice模型链接的外键字段。
models.py
class Choice(models.Model):
name = models.ForeignKey(Person)
photo_other = models.ForeignKey(Person)
rating = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return smart_unicode(self.name)
class Person(models.Model):
name = models.CharField(max_length=250)
photo = models.ImageField(upload_to="photos")
pub_date = models.DateTimeField()
def __unicode__(self):
return smart_unicode(self.name)
通过foreign key
连接时,为什么要在两个不同的表中存储相同的值? 只是没有意义。
class Choice(models.Model):
name = models.ForeignKey(Person)
rating = models.DateTimeField(blank=True, null=True)
@property
def photo_other(self):
return self.name.photo
class Person(models.Model):
name = models.CharField(max_length=250)
photo = models.ImageField(upload_to="photos")
pub_date = models.DateTimeField()
为了使photo_other
在Choice
模型的管理页面下可见,您可以执行以下操作;
class ChoiceAdmin(admin.ModelAdmin):
list_display = ['name', 'rating', 'get_photo']
def get_photo(self, obj):
return obj.photo_other
get_photo.short_description = 'Photo'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.