【问题标题】:How to show child table in Django REST Framework API view如何在 Django REST Framework API 视图中显示子表
【发布时间】:2021-08-17 22:24:16
【问题描述】:

我使用 Django 作为 Backend,使用 PostgresSQl 作为 DB,使用 HTML、CSS 和 Javascript 作为前端。我想在DJANGO REST FRAMEWORK 中显示儿童表,因为我正在使用多表继承

正如我们在上图中看到的,只显示了产品列表,但没有显示子表。我想显示客户选择的所有数据。我在 DRF 中显示购物车产品

views.py

class AddToCartView(TemplateView):
    template_name = "status.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        product_id = self.kwargs['pk']
        product_obj = Product.objects.get(id = product_id)
        cart_id = self.request.session.get("cart_id", None)
        if cart_id:
            cart_obj = Cart.objects.get(id = cart_id)
            this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj)
        
            if this_product_in_cart.exists():
                cartproduct = this_product_in_cart.last()
                cartproduct.quantity += 1
                cartproduct.subtotal += product_obj.price
                cartproduct.save()
                cart_obj.total += product_obj.price
                cart_obj.save()
            else:
                cartproduct = CartProduct.objects.create(
                    cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)
                cart_obj.total += product_obj.price
                cart_obj.save() 
        else:
            cart_obj = Cart.objects.create(total=0)
            self.request.session['cart_id'] = cart_obj.id
            cartproduct = CartProduct.objects.create(
                cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)
            cart_obj.total += product_obj.price
            cart_obj.save()

        return context

API 视图 (views.py)

@api_view(['GET'])
def showproduct(request):
    result = CartProduct.objects.all()
    serialize = productserializers(result, many = True)
    return Response(serialize.data)

models.py

class Product(models.Model):
    name = models.CharField(max_length=1330)
    image_src = models.URLField(max_length=1330,null=True, blank=True)
    link_href = models.URLField(max_length=1330,null=True, blank=True)
    brand = models.CharField(max_length = 1330, null=True, blank=True)
    price = models.DecimalField(max_digits=15, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created',)


class Refrigerator(Product):
    series = models.CharField(max_length = 300, null=True, blank=True)
    model = models.CharField(max_length = 300, null=True, blank=True)
    ...

class Cart(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    total = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Cart: " + str(self.id)


class CartProduct(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField()
    quantity = models.PositiveIntegerField()
    subtotal = models.PositiveIntegerField()

    def __str__(self):
        return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id)

我想在客户选择的 DRF 中也显示冰箱的详细信息。

serializer.py

class productserializers(serializers.ModelSerializer):
    class Meta:
        model = CartProduct
        fields = "__all__"
        depth = 2

【问题讨论】:

  • 为什么要创建冰箱模型?
  • 其实,我想在我的网站上这样工作。 link。我希望所有列表都显示在一页上。有规范。所以这就是我这样做的原因
  • @KiranChauhan 的做法是否正确?
  • 只创建一个产品表并在表中添加 1 个字段,如“类型”,这样您就可以添加多种类型的产品“风扇”、“冰箱”..等等我已经在之前的答案中向您展示过如何将产品表与类别表链接
  • 好的,我会尽力让你知道

标签: python django django-models django-rest-framework django-views


【解决方案1】:

你可以试试这个,在你的Product(models.Model)

 class Meta:
        abstract = True

你可以参考这里的解释:here (我应该对此发表评论,但没有足够的声誉:/)

【讨论】:

  • 您好,Rahul,我遇到了错误。 Field defines a relation with model 'Product', which is either not installed, or is abstract
  • @santoshChauhan 现在您必须在冰箱模型中添加 Product 作为外键才能使其正常工作,查看此链接可能会有所帮助 link
  • 你好 Rahul ,正如你所说我必须使用 abstract = True ,这对我没有帮助,因为当你看到我的 CartProduct 模型时,我正在使用 Product 模型作为基类和我的问题是唯一的一件事是,我无法使用用户选择的父表访问子表。我想在 DRF 中显示,是选择了哪个子模型,而我的 DRF 显示了 Only Parent 表。
  • @santoshChauhan,我认为它会起作用,现在解决了吗?
  • 没有兄弟,它不能为我解决吗?现在我为不同的模型制作不同的应用程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多