我试图在Django中为用户进行查询,但仍然每个用户都可以看到数据库中的所有数据。我试过使用过滤器、q对象,但这些都对我没有帮助
这是我的型号:
class Book(models.Model):
def __str__(self):
return f'{self.bookIdent} - belonging to: {self.user}'
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bookIdent = models.CharField(max_length=255)
bookshelf = models.ForeignKey(BookShelf, default='', on_delete=models.CASCADE)
@classmethod
def total_info(cls):
return cls.objects.aggregate(book_counter=Count('id'))
class Meta:
verbose_name_plural = "Books"
我的观点:
@login_required(login_url="/login/")
def index(request):
context = {'segment': 'index'}
html_template = loader.get_template('dashboard.html')
context.update(dict(Book.total_info()))
context['Book'] = set_pagination(request,Book.objects.all().
filter(user=request.user), item_numer=10)
return HttpResponse(html_template.render(context, request))
我想查询一下,只有图书类的用户才能看到他的书。
模板:
<div class="col-xl-3 col-md-6">
<div class="card card-stats">
<div class="card-body">
<div class="row">
<div class="col">
<h5 class="card-title text-uppercase text-muted mb-0">Book quantity:</h5>
<span class="h2 font-weight-bold mb-0">
{{ book_counter|default:0 }}
</span>
</div>
在您的views.py中,您可以执行
books = Book.objects.filter(user=request.user)
context['book_counter'] = books.count()