1

Now i could use list_display( ) to show the column word and click_times when using Click_Data models. The code is below:

# models.py
class Click_Data(models.Model):
    word = models.CharField(max_length=255)
    click_times = models.IntegerField(default=0)

    class Meta:
        ordering = ('word',)

    def __unicode__(self):
        return self.word  

# admin.py
    class Click_DataAdmin(admin.ModelAdmin):
        fieldsets = [
            ('Word',    {'fields': ['word']}),
            ('Number',  {'fields': ['click_times']}),
        ]
        list_display = ('word', 'click_times')

But i don't know how to use list_display( ) to show the column word and click_times when using the User_Data models(which is below).

# models.py
class User_Data(models.Model):
    user = models.ForeignKey(User)
    click_data = models.ForeignKey(Click_Data)

    class Meta:
        ordering = ('user',)

    def __unicode__(self):
        return unicode(self.user)

# admin.py
class User_DataAdmin(admin.ModelAdmin):
    fieldsets = [
        ('User',    {'fields': ['user']}),
        ('Word',    {'fields': ['click_data']}),
    ]
    list_display = ('user', 'click_data')

I want to show the not only the 'word' in 'click_data' but also 'click_times', how could i achieve this?

Paulo Pessoa
  • 2,509
  • 19
  • 30
Peter Tsung
  • 915
  • 2
  • 10
  • 20

1 Answers1

10

Try this:

class User_DataAdmin(admin.ModelAdmin):
    ...
    list_display = (..., 'get_click_times', 'get_word')

    def get_click_times(self, obj):
        return obj.click_data.click_times

    get_click_times.short_description = 'Click Times'

    def get_word(self, obj):
        return obj.click_data.word

    get_word.short_description = 'Word'
Paulo Pessoa
  • 2,509
  • 19
  • 30