Django - Include data from foreignkey in admin list_display function

前端 未结 3 1068
野的像风
野的像风 2021-01-20 03:48

I have two models and one admin model:

class Person(models.Model):

    firstname = models.CharField(maxlength=50)
    surname = models.CharField(maxlength=5         


        
相关标签:
3条回答
  • 2021-01-20 04:01

    Thans for your Answer uvasal (it was very helpful) but this code has invalid syntax

    you need: return '%s'%(obj.book.review,) or return '%s' % obj.book.review

    0 讨论(0)
  • 2021-01-20 04:11

    This code isn't complete - you've got two ForeignKeys from Friends to Person, so at least one of them will need a related_name attribute to prevent clashes. The code simply won't run as it is.

    If a Person can only be friends with one other person, you should use a OneToOneField rather than a ForeignKey. Then, you can simply refer to my_person.friend1.person1.surname, where my_person is the Person you starting with, and friend1 is the related_name value I mentioned above.

    0 讨论(0)
  • 2021-01-20 04:21

    You need to create something like this in your FriendAdmin class:

    class UserAdmin(admin.ModelAdmin):
        list_display = (..., 'get_reviews')
    
        def get_reviews(self, obj):
            return obj.book.review
        get_reviews.short_description = 'Review'
    
    0 讨论(0)
提交回复
热议问题