简体   繁体   English

在django-admin中从queryset获取属性

[英]Getting attributes from queryset in django-admin

I would like to use a queryset( queryset) in django-admin to get all the objects. 我想在django-admin中使用queryset( queryset)来获取所有对象。 Based on the queryset achieved, i would like to display certain attributes of the queryset for viewing. 基于实现的查询集,我想显示查询集的某些属性以供查看。 For example, I would like to show the person's id, the person's parent, the person's parentname,email and so on. 例如,我想显示此人的ID,该人的父母,该人的父母姓名,电子邮件等。

The example provided in Django docs is: Django docs中提供的示例是:

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

I would definitely like to improve on this. 我肯定会对此进行改进。

I have tried something like this: 我已经尝试过这样的事情:

class ChildParentAdmin(admin.ModelAdmin):
    list_display = ('displayname', 'StudentID',)
    search_fields = ['displayname',]

    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
    def StudentID(self,queryset):
        for student in queryset:
            return student.pk

The point i am stuck in how do you use the queryset and perform further actions like getting the id of each child, name of parent of each child and so on... Would like some guidance on going about doing this.Would really appreciate any help on this.. Thanks... 我停留在如何使用queryset并执行进一步的操作(例如获取每个孩子的ID,每个孩子的父母的姓名等等)上的要点……希望对此有一些指导。帮助这个..谢谢...

def StudentID(self, obj):
  return '%s' % obj.pk
StudentID.short_description = 'StudentID'
def Student_Name(self, obj):
    return '%s' % obj.name

This is the correct way of doing it.. You don't have to query over all the objects in queryset. 这是做它的正确途径。你不必在查询中查询集的所有对象。 Just need to pass the obj. 只需要传递obj。 It will run it for all objects. 它将对所有对象运行它。 There are other ways of doing this, which doesn't involve the class itself..To read more on this, please look at list_display Django Admin . 还有其他方法可以执行此操作,而这些方法不涉及类本身。要了解更多信息,请查看list_display Django Admin The examples are very clear. 例子很清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM