モデルシリアライザーを使用して、django-rest-frameworkの外部キーの単一のインスタンスまたは行に異なる多対多フィールドを追加する方法

Abhinav Jha

Django-rest-frameworkとreactを使用してeコマースウェブサイトを作成しています。カートに商品を追加しようとしています。フロントエンドでカートにアイテムを追加することはできますが、カートデータをバックエンド(Django)データベースに保存して、ユーザーがカートにアイテムを追加してページをリロードするたびに、アイテムが他のカートと同じようにカートに残るようにします。他のeコマースサイト。これが、djangoモデル、シリアライザー、ビューセットのコードです。

class Products(models.Model):
    title = models.CharField(max_length=100)
    image = models.URLField()
    description = models.TextField(max_length=500, blank=True, null=True)
    category = models.CharField(max_length=50, blank=True, null=True)
    rating = models.IntegerField(blank=True, null=True)
    price = models.FloatField()

    def __str__(self):
        return f"{self.id}"

class Cart(models.Model):
    product = models.ManyToManyField(
        Products, related_name="cart")
    buyer = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="cart")

    def __str__(self) -> str:
        return f"{self.buyer}"
class ProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = '__all__'

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = '__all__'

class ProductsViewSet(viewsets.ModelViewSet):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializer

class CartViewSet(viewsets.ModelViewSet):
    queryset = Cart.objects.all()
    authentication_classes = [JWTAuthentication]
    permission_classes = [
        permissions.IsAuthenticated
    ]
    serializer_class = CartSerializer

router = routers.DefaultRouter()
router.register('products', ProductsViewSet, 'products')
router.register('cart', CartViewSet, 'cart')

私は郵便配達員を使ってカートアイテムを投稿しています。1人の購入者に複数の商品を追加できます。

but the problem is when i again add another product to the same user using postman i added before, it creates another row for the same user.

I do not want that. I want a single instance or row of a user in cart table and add as many products as i want. when i post other products for the same user, that product should also get added up in the single user row or instance. What is the best way to achieve my goal.

Divyansh Rai

Here is the issue, Django can't automatically do that because it doesn't know which behaviour is expected. If you look at the code to add a product and look at the code to add a cart, it's exactly the same. So behaviour will also be the same.

For the behaviour that you want, you will have to override the create method of your ModelViewSet. Here are the steps to achieve what you want -

  1. Check whether or not the user with that id already has a cart.

  2. If they have a cart, then you'll need to fetch the cart object belonging to that user and add products to it.

  3. If they don't, then you'll have to create a new cart object and do the default thing.

    class CartViewSet(viewsets.ModelViewSet):
        queryset = Cart.objects.all()
        authentication_classes = [JWTAuthentication]
        permission_classes = [
            permissions.IsAuthenticated
        ]
        serializer_class = CartSerializer
    
        def create(self, request):
            # Checking whether the Cart object already exists for the buyer
            cart = Cart.objects.filter(buyer_id = request.data.get("buyer"))
    
            if len(cart)=1:
                #If cart exists, we loop through the list of product ids and add them
                for product_id in request.data.get("product"):
                    cart[0].product.add(get_object_or_404(Product, id = product_id ))
    
            if len(cart)=0:
                # Doing what normally happens.
                return super().create(request)
    
            if len(cart)>1:
                #Error in database. One person having multiple carts. Custom error message.
    

To check out how to add data to many-to-many fields, check this out.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

TOP 一覧

  1. 1

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  2. 2

    CSSのみを使用して三角形のアニメーションを作成する方法

  3. 3

    ZScalerと証明書の問題により、Dockerを使用できません

  4. 4

    ドロップダウンリストで選択したアイテムのQComboBoxスタイル

  5. 5

    別のホストからTomcat Managerアプリにアクセスする

  6. 6

    PyCharmリモートインタープリターはプロジェクトタブにサイトパッケージのコンテンツを表示しません

  7. 7

    Windows 10でのUSB入力デバイスの挿入/取り外しの検出

  8. 8

    Python / SciPyのピーク検出アルゴリズム

  9. 9

    MLでのデータ前処理の背後にある直感

  10. 10

    useRefに反応してコンポーネントをスクロールして表示する

  11. 11

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  12. 12

    パンダは異なる名前の列に追加します

  13. 13

    PictureBoxで画像のブレンドを無効にする

  14. 14

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  15. 15

    Pythonを使用して、リストからデータを読み取り、特定の値をElasticsearchにインデックス付けするにはどうすればよいですか?

  16. 16

    LinuxでPySide2(Qt for Python)をインストールするQt Designerはどこにありますか?

  17. 17

    Material-UIでTextFieldエラーの色を条件付きでオーバーライドする方法

  18. 18

    goormIDEは、ターミナルがロードするデフォルトプロジェクトを変更します

  19. 19

    MatplotlibまたはSeabornを使用して、グループ化されたデータから複数のプロットを生成するにはどうすればよいですか?

  20. 20

    Luaの文字列から特定の特殊文字を削除するにはどうすればよいですか?

  21. 21

    Flutterにファイルピッカープラグインを追加するにはどうすればよいですか?

ホットタグ

アーカイブ