简体   繁体   中英

fetching data using query from a particular table and showing it in admin side of django

I am working on a Django project and I want to fetch data from particular table and show it in the admin side.

I am having a Company model which I have registered in admin using admin.site.register(Company, Company_Admin) . Now I want to just get all the companies after querying them from the table and just show the result in the admin site.

class Company(models.Model):
    name = models.CharField(default=None,max_length=200)
    description = models.TextField(default=None)
    url = models.CharField(max_length=200)
    published = models.BooleanField()
    createdOn = models.DateTimeField(default=datetime.utcnow)
    updatedOn = models.DateTimeField(default=datetime.utcnow)
    keywords = models.ManyToManyField(Keyword)

    def __unicode__(self):
       return self.text

class CompanyAdmin(admin.ModelAdmin): 
    list_display = ['name', 'url', 'description', 'published', 'createdOn', 'updatedOn']
    list_filter = ['name']
    search_fields = ['name']
    filter_horizontal = ('keywords', )

admin.site.register(Company, CompanyAdmin)

Now I want to create an option in admin panel that will show me all the companies that are published, that is, do not even show the non-published companies.

Try to add list_filter in CompanyAdmin on 'published':

list_filter = ['name','published']

So, You can find one pane at right side, in which you can just filter out as you want. (I'm considering that you're not overriding default admin template.)

According to the docs on ModelAdmin.list_filter , you can try adding the field name to that attribute. This should give you a new filter option in the right sidebar of the change view.

class CompanyAdmin(admin.ModelAdmin): 
    ...
    list_filter = ['name', 'published']
    ...

If, however, you want to hide all non-published instances completely from the admin (I don't know if that is the case, I don't fully understand you question), then you can modify the ModelAdmin.get_queryset() method .

class CompanyAdmin(admin.ModelAdmin): 
    ...
    def get_queryset(self, request):
        return super().get_queryset(request).filter(published=True)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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