Django / RestFramework:如何从具有外键的模型中获取数据

时间:2018-05-06 15:02:48

标签: django django-rest-framework

我有两个模型

class Shops(models.Model):
    shopkeeper = models.ForeignKey(Shopkeeper, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    category = models.CharField(max_length=250)
    contactNumber = models.IntegerField()
    address = models.CharField(max_length=500)
    dateCreated = models.DateTimeField(auto_now_add=True)

class Product(models.Model):
    productsubcategory = models.ForeignKey(ProductSubCategory, on_delete=models.CASCADE)
    shop = models.ForeignKey(Shops, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    price = models.IntegerField()
    image = models.FileField(null=True)
    detail = models.TextField()
    quantity = models.IntegerField()
    dateCreated = models.DateTimeField(auto_now_add=True)

我为产品型号制作了序列化程序类。我想写一个View应该返回特定商店的产品。我的观点如下,

class ShopkeeperProductAPIView(generics.GenericAPIView):
    def get(self,request,shop_id):
        products = Product.objects.get(shop=shop_id)
        products_serializer = ProductSerializer(products, many=True)
        return Response(products_serializer.data)

我的网址如下,

path('shops/products/<int:shop_id>', views.ShopkeeperProductAPIView.as_view())

请帮帮我。

2 个答案:

答案 0 :(得分:1)

你不能使用:

products = Product.objects.get(shop=shop_id)

由于您使用了get()方法,因此只会返回一个产品。您必须在序列化程序中使用filter()many=True

所以代码看起来像:

class ShopkeeperProductAPIView(generics.GenericAPIView):
    def get(self,request,shop_id):
        products = Product.objects.filter(shop=shop_id)
        products_serializer = ProductSerializer(products, many=True)
        return Response(products_serializer.data)

答案 1 :(得分:1)

Is there any reason why, from all tools that DRF provides, you are using only serializers? Here's how I would created products endpoint. In createform.addEventListener("submit", function(e) { e.preventDefault(); var msg = window.confirm("Want to go to other page?"); if (msg) { window.location.href = "url"; } }) :

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout"
        android:layout_below="@id/imgbtnGrub"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="150dp"
        android:layout_height="250dp"
        android:layout_below="@+id/imgbtnGrub"
        android:layout_alignParentBottom = "true">


        <ListView
            android:id="@+id/navList"
            android:layout_width="150dp"
            android:layout_height="match_parent"
            android:layout_gravity="left|start"
            android:alpha="0.75"
            android:background="#ffee33"
            android:divider="@null"
            android:theme="?attr/textAppearanceListItemSmall" />

    </android.support.v4.widget.DrawerLayout>
    </LinearLayout>

And in viewsets.py:

class ShopkeeperProductViewSet(viewsets.ViewSet):

    def list(self, request):
        queryset = Product.objects.all()
        serializer = ProductSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Product.objects.filter(shop=pk)
        serializer = ProductSerializer(queryset, many=True)
        return Response(serializer.data)