简体   繁体   中英

Django Model set @property with filter and show it on template

I have case that need to count and show user that doesn't have a blog.

here my views.py

class Blog(models.Model):
    desc = models.TextField(blank=True, null=True)
    user = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name='blogs')

    @property
    def DOESN_HAVE_BLOG(self):
        blog = Self.Blog.all().values_list('user', flat=True)
        value = Self.User.exclude(id__in=blog)
        return value

here mytemplate.html

{{ DOESN_HAVE_BLOG.count }}

but its doesn't work

This is not something that you would do as a model property. A property relates to an actual instance of Blog, but you are looking for Employees that have no instances at all.

Instead, you should do the query separately in the view - a good place for this is in get_context_data .

class MyView(ListView):
    ...
    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)
        data['DOESN_HAVE_BLOG'] = Employee.objects.filter(blog=None)
        return data

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