Django管理面板与filter_horizo​​ntal

时间:2014-12-28 12:48:46

标签: python django admin

我有2个表:users: id, nameuser_follow: id, user_id, follow_user_id

#model.py
class User(models.Model):
    name = models.CharField(max_length=32)
    follow = models.ManyToManyField('self', symmetrical=False, related_name = 'followed', verbose_name='followed')
    class Meta:
        managed = True

    def __str__(self):
        return "%s, id=%s" % (self.name, self.id)

class Follow(models.Model):
    '''Describes follow relation between Man instances: who follows whom'''
    who = models.ForeignKey('User', related_name='who')
    whom = models.ForeignKey('User', related_name='whom')

#admin
class UserAdmin(admin.ModelAdmin):
    list_display = ('name', 'len_follows', 'len_followed_by')
    list_display_links = ('name',)
    inlines = [FollowsInline, FollowedInline]

    filter_horizontal = ['follow']

我需要再添加一个filter_horizo​​ntal来显示关注此用户的用户。

1 个答案:

答案 0 :(得分:3)

thx我在这里找到答案,这个snipet帮了我很多https://snipt.net/chrisdpratt/symmetrical-manytomany-filter-horizontal-in-django-admin/

#admin
class UserAdminForm(forms.ModelForm):
        followers = forms.ModelMultipleChoiceField(
            label="Followers", queryset=Users.objects.all(),
            initial=user.followers.all(),
            widget=admin.widgets.FilteredSelectMultiple("followers", False),
            required=False
        )

        class Meta:
            model = User
            fields = ("name", "follow", "followers")

        def save(self, commit=True):
            instance = super(UserAdminForm, self).save(commit)
            instance.followers = self.cleaned_data.get("followers", [])
            return instance

    return UserAdminForm

class UserAdmin(admin.ModelAdmin):
    list_display = ("name", "follow_count", "followers_count")
    filter_horizontal = ("follow",)


    def get_form(self, request, obj=None, **kwargs):
        if obj is not None:
            self.form = make_user_admin_form(obj)
        return super(UserAdmin, self).get_form(request, obj, **kwargs)