Django-如何按用户过滤购买的书籍

时间:2019-04-21 08:33:35

标签: django django-models django-views

我创建了一个模型,允许用户购买书籍。正在识别正在购买的书,但是当用户访问书的内容时,会发生以下错误:get()返回了多个Purchase_Book -返回了2!

我已经尝试过调整代码,但无济于事。

这是我的模型及其相互之间的联系。

class Book(models.Model):
      # some book info

      def __str__(self):
          return self.title

      def get_absolute_url(self):
         return reverse('book-detail', kwargs={'slug': self.slug})

      @property
      def pages(self):
          return self.page_set.all()

这本书的内容

class Page(models.Model):
    # some pdf files to upload

    def __str__(self):
        return self.slug

    def get_absolute_url(self):
        return reverse('page-detail',
                   kwargs={
                       'book_slug': self.book.slug,
                       'page_slug': self.slug
                   })

能够过滤可以访问该书内容的用户的模型。

class Purchase_Book(models.Model):
    description = models.CharField(max_length=50, null=True)
    selected_Book = models.ManyToManyField(Book)

    def __str__(self):
        return self.description

class Customer(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE)
       service_Type = models.ForeignKey(Purchase_Book, on_delete=models.CASCADE, null=True)

      def __str__(self):
         return self.user.email

这是我的最新views.py,我在这里过滤可以访问该书内容的用户。

class PageDetailView(NeverCacheMixin, LoginRequiredMixin, generic.View):

def get(self, request, book_slug, page_slug, *args, **kwargs):
    book = get_object_or_404(Book, slug=book_slug)
    page = get_object_or_404(Page, slug=page_slug)
    purchased = get_object_or_404(Purchase_Book)
    user_membership = get_object_or_404(Customer, user=request.user)
    user_membership_type = user_membership.service_Type.selected_Book

    user_allowed = purchased.selected_Book.all()

    context = {'object': None}
    if user_allowed.filter(selected_Book=user_membership_type).exists():
        context = {'object': page}
    return render(request, "catalog/page_detail.html", context)

我仍然是初学者。我希望有一个人可以帮助我。

1 个答案:

答案 0 :(得分:2)

我认为错误是由于以下几行:

purchased = get_object_or_404(Purchase_Book)

如果创建了多个Purchased_Book,则会引发错误。理想情况下,您需要提供一个条件(或参数)来获取实际对象,即get_object_or_404(Purchase_Book, pk=1)

顺便说一句,您可以删除该行并为特定客户获取购买的图书,如下所示:

user_membership = get_object_or_404(Customer, user=request.user)
purchased = user_membership.service_Type

此外,我认为根本不需要以下几行(代码注释中的解释):

user_membership_type = user_membership.service_Type.selected_Book  # getting current user books

user_allowed = purchased.selected_Book.all()  # getting current user books

context = {'object': None}
if user_allowed.filter(selected_Book=user_membership_type).exists():  # comparing books ? Why? You can remove that, because you are already getting current user books. 
# if there is a relation between page and user, you should put logic for that here instead of current one

更新

类似这样的东西应该可以工作:

if purchased.selected_Book.filter(pk=page.book.pk).exists()
   context = {'object': page}