Home > Software engineering >  How to save data from API to my MySQL database in Django REST project
How to save data from API to my MySQL database in Django REST project

Time:12-06

I have a Django REST project. There is a model Product. I get some data from marketplace API about products stocks. And I need to save it to my datbase. I don't know, what kind of viewsets to choose. And how to make a create method. Thanks.

My Product model `

class Product(models.Model):
    store = models.ForeignKey(
        Store,
        on_delete=models.PROTECT, blank=True,
                            verbose_name="Store")
    offer_id = models.CharField(max_length=50,
                            blank=True,
                            default="",
                            verbose_name="SKU")
    name = models.CharField(max_length=128,
                            blank=True,
                            default="",
                            verbose_name="Name")
    present = models.PositiveIntegerField(
                            default=0,
                            verbose_name="Present")
    reserved = models.PositiveIntegerField(
                            default=0,
                            verbose_name="Reserved")

` My serializer

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = '__all__'

    store = serializers.CharField()
    offer_id = serializers.CharField()
    name = serializers.CharField()
    present = serializers.IntegerField()
    reserved = serializers.IntegerField()

The data I get from API is a list, for example:

[
   {
      "offer_id":"1-100-3-0",
      "present":5,
      "reserved":1
   },
   {
      "offer_id":"1-101-3-9",
      "present":0,
      "reserved":0
   }
]

CodePudding user response:

Refer the doccumentation for more

here is how you do it

@api_view([ 'POST'])
def product_post(request):
    if request.method == 'POST':
       serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

and urls should be

path('product_post/', views.product_post, name='product_post'),

CodePudding user response:

I creat a Modelviewset, it works with out errors, but stocks aren't saved in DB. I tried to create and run a test, but I have

self.assertEqual(len(Product.objects.filter(store__user_id=self.user.pk)), 1)

AssertionError: 0 != 1

So, I can't find a reason.

class ProductApi(ModelViewSet):

serializer_class = ProductSerializer
permission_classes = (IsAuthenticated,)

def get_queryset(self):
    return Product.objects.filter(
        store__user_id=self.request.user.pk)\
        .order_by('-offer_id')

def create(self, request, *args, **kwargs):
    st = Store.objects.filter(user=self.request.user,
                              type=1)
    for _ in st:
        api = Parser(api_key=_.api_key,
                            client_id=_.client_id)
        data = api.get_product_info_stocks()
        if len(data) > 0:
            for stock in data:
                if Product.objects.filter(
                                offer_id=stock.get('offer_id')).exists():
                    pass
                else:
                    stock_data = {
                        'offer_id': stock['offer_id'],
                        'present': stock['present'],
                        'reserved': stock['reserved']
                    }
                    Product.objects.create(**stock_data)
            stocks = Product.objects.filter(
                store__in=st).order_by(
                '-offer_id')
            s = ProductSerializer(stocks, many=True)
            return Response(status=200, data=s.data)
        else:
            return Response(status=204,
                            data={"Info": "Empty response"})
    return Response(status=400,
                    data={"Message": "User has no stores"})
  • Related