Home > database >  Save all data in database with one query in Django
Save all data in database with one query in Django

Time:01-21

I'm a new Django programmer. I write a API call with rest_framework in Django. when call this API, my program connect to KUCOIN and get list of all cryptocurrency. I want save symbol and name this cryptocurrencies in database. For save data to database, I use 'for loop' and in every for loop iteration, I query to database and save data. my code :

for currencie in currencies:
    name = currencie['name']
    symbol = currencie['symbol']
    active = (False, True)[symbol.endswith('USDT')]
    oms = 'kucoin'

    try:
        obj = Instrument.objects.get(symbol=symbol, oms=oms)
        setattr(obj, 'name', name)
        setattr(obj, 'active', active)
        obj.save()
    except Instrument.DoesNotExist:
        obj = Instrument(name=name, symbol=symbol,
                            active=active, oms=oms)
        obj.save()

query to database in every for loop iteration have problem ,How can I solve this problem? Exist any way in Django to save data in database in with one query. All my code:

class getKucoinInstrument(APIView):
    
    def post(self, request):
        try:
            person = Client.objects.filter(data_provider=True).first()
            person_data = ClientSerializer(person, many=False).data
            api_key = person_data['api_key']
            api_secret = person_data['secret_key']
            api_passphrase = person_data['api_passphrase']

            client = kucoin_client(api_key, api_secret, api_passphrase)
            currencies = client.get_symbols()

            for currencie in currencies:
                name = currencie['name']
                symbol = currencie['symbol']
                active = (False, True)[symbol.endswith('USDT')]
                oms = 'kucoin'

                try:
                    obj = Instrument.objects.get(symbol=symbol, oms=oms)
                    setattr(obj, 'name', name)
                    setattr(obj, 'active', active)
                    obj.save()
                except Instrument.DoesNotExist:
                    obj = Instrument(name=name, symbol=symbol,
                                     active=active, oms=oms)
                    obj.save()

            return Response({'response': 'Instruments get from kucoin'}, status=status.HTTP_200_OK)

        except Exception as e:
            print(e)
            return Response({'response': 'Internal server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Thank you for you help.

CodePudding user response:

Yes! Take a look at bulk_create() documentation. https://docs.djangoproject.com/en/4.0/ref/models/querysets/#bulk-create

If you have a db that supports ignore_conflicts parameter (all do, except Oracle), you can do this:

new_currencies = []
for currencie in currencies:
    name = currencie['name']
    symbol = currencie['symbol']
    active = (False, True)[symbol.endswith('USDT')]
    oms = 'kucoin'
    new_currencies.append(Instrument(name=name, symbol=symbol,
                        active=active, oms=oms))
Instrument.objects.bulk_create(new_currencies, ignore_conflicts=True)

1-liner:

Instrument.objects.bulk_create(
[
    Instrument(
        name=currencie['name'], symbol=currencie['symbol'], 
        active=currencie['symbol'].endswith('USDT'), oms='kucoin'
    )
    for currencie in currencies
], 
ignore_conflicts=True
)

CodePudding user response:

In Django, If you want to save data in database you need to create new class object:

for currencie in currencies:
 name = currencie['name']
 symbol = currencie['symbol']
 active = (False, True)[symbol.endswith('USDT')]
 oms = 'kucoin'

 try:
    obj = Instrument.objects.get(symbol=symbol, oms=oms)
    obj.name = name
    obj.active = active
    obj.save()
 except Instrument.DoesNotExist:
    obj = Instrument.objects.create(symbol=symbol, oms=oms, name =name, active=active)
    obj.save()

for more documentation see thins link : https://docs.djangoproject.com/en/4.0/ref/models/querysets/#create

  •  Tags:  
  • Related