Django -如何在另一个应用模型上获取对象,而不与父模型直接关联?

hyrbngr7  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(98)

我有一个Profile modelAward model作为Profile模型的子模型[它获取其他奖励详细信息,如成就详细信息],还有一个List_of_awards model作为Award模型的子模型[它获取奖励列表和拥有特定奖励的配置文件的数量]。
Award modelProfile model保持一致,使用ForeignkeyList_of_awards model作为Award model中的Foreignkey field,以选择奖励。
我尝试做的是在Profile model中显示List_of_awards。这个想法起源于我能够在Award model', so, I was trying to link List_of_awards in the Profile '的list_display中显示List_of_awards,这没有直接关系。

class Profile(models.Model):
     first_name                          = models.CharField(verbose_name=_('First Name'), max_length=255, null=True, blank=True, )
     middle_name                         = models.CharField(verbose_name=_('Middle Name'), max_length=255, null=True, blank=True)
     last_name                           = models.CharField(verbose_name=_('Last Name'), max_length=255, null=True, blank=True)
     ....

class Award(models.Model):
    list_of_award       = models.ForeignKey('system_settings.Ribbon', related_name='awards_ad_ribbon', on_delete=models.DO_NOTHING, verbose_name=_('Type of Award'), blank=True, null=True)
    achievement         = models.TextField(verbose_name=_('Achievement'))
    profile             = models.ForeignKey('reservist_profile.Profile', related_name='awards_ad_profile', verbose_name=_('Profile'), on_delete=models.DO_NOTHING, blank=True, null=True)

     def image_tag(self):
        from django.utils.html import format_html
        return format_html('<img src="/static/media/%s" title="" width="75" /> %s' % (self.list_of_award.image,self.list_of_award.award))
     image_tag.short_description = 'Award'

class Ribbon(models.Model):
award      = models.CharField(verbose_name=_('Award'), max_length=255, null=True, blank=True)
award_desc = models.TextField(verbose_name=_('Description'), max_length=255, null=True, blank=True)
image       = models.ImageField(verbose_name = _('Image'), upload_to = award_image_location, blank = True, null = True)

class Meta:
    verbose_name = _('List of awards')
    verbose_name_plural = _('List of awards')

def __str__(self):
    return '%s' % (self.award)

def image_tag(self):
    return format_html('<img src="/static/media/%s" width="75" />' % (self.image))

image_tag.short_description = 'Award Image'

所以,这就是我目前所拥有的,其他功能是通过研究得出的,但在这个特定的场景中,我不知道搜索关键字是什么,所以如果有人已经问过了,我很抱歉。谢谢。

polhcujo

polhcujo1#

你可以这样尝试:

class ProfileAdmin(admin.ModelAdmin):
    list_display = ('first_name',... 'list_of_awards')
    
    @admin.display(description='Awards')
    def list_of_awards(self, obj):
        return ",".join([k.list_of_award.award for k in obj.awards_ad_profile.all()]

更多信息可在文档中找到。

相关问题