简体   繁体   中英

How to populate the Django Model with the data fetched from the external site?

From the external site thru API, I have fetched the dictionary data that I want to save it to the Django Model.

I have tried to save the data to the Django Model at the models.py but failed.

In the models.py , I wrote the def get_save(self, request) like the following.

class AirData(models.Model):
    co = models.DecimalField(max_digits=5, decimal_places=2)
    no2 = models.DecimalField(max_digits=5, decimal_places=2)
    so2 = models.DecimalField(max_digits=5, decimal_places=2)
    pm10 = models.DecimalField(max_digits=5, decimal_places=2)
    pm25 = models.DecimalField(max_digits=5, decimal_places=2)
    datatime = models.DateTimeField(blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    station = models.CharField(max_length=80)

    def get_save(self, request):

            url = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"

            params = {'stationName': '강남구', 'dataTerm': 'month', 'pageNo': '1', 'numOfRows': '10',
                      '_returnType': 'json', 'ServiceKey': service_key, 'ver': '1.3'}
            airdata_dict = get_airdata(url, service_key, params)

            self.co = airdata_dict['coValue']
            self.save()

But the airdata_dict , fetched from the url, is not saved to the instance.

Please help me show how to save data in the Model.


Based on the suggestions of @HariHaraSudhan, I changed the views.py as follows

def get_value(self):
    url = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"

    params = {'stationName': '강남구', 'dataTerm': 'month', 'pageNo': '1', 'numOfRows': '10',
              '_returnType': 'json', 'ServiceKey': service_key, 'ver': '1.3'}
    airdata_dict = get_airdata(url, service_key, params)
    airdata_list = airdata_dict['airdata']
    kwargs = dict()
    for data in airdata_list:
        kwargs['station'] = data['stationName']
        kwargs['co'] = data['coValue']
        kwargs['no2'] = data['no2Value']
        kwargs['so2'] = data['so2Value']
        kwargs['o3'] = data['o3Value']
        kwargs['pm10'] = data['pm10Value']
        kwargs['pm2.5'] = data['pm25Value']
        kwargs['time'] = data['dataTime']

    obj = AirData.objects.create(self.kwargs)

And the models.py is also changed as:

class AirData(models.Model):
    @classmethod
    def create(cls, **kwargs):
        my_obj = cls(kwargs)
        return my_obj

But the error pops up as AttributeError: 'WSGIRequest' object has no attribute 'kwargs' .

Your model method get_save should work if:

  1. You make sure you cast the strings received by the API ( airdata['coValue'] ) to the correct type, eg for co :

     self.co = Decimal(airdata['coValue']) 

    Beware also that your dates are strings, so you need to change them to a proper datetime.datetime if you're going to assign them.

  2. You make sure all required fields are set before saving ( self.no2 is required, so if it's None , your model will not save). You should see an error in that case.

An easier way is to create a dictionary of all the correct values, eg

kwargs['co'] = Decimal(airdata['coValue'])
...

and pass it to the ModelManager 's create() method:

MyModel.objects.create(**kwargs)

Make sure all the keys in the dictionary correspond to fields of your model.

I think better way to create is using alternative constructor .

class MyModel(models.Model):
    @classmethod
    def create(cls, **kwargs):
        my_obj = cls(kwargs)
        return my_obj

In view get the value from API

def get_value(self):
    kwargs = dict()
    kwargs['co'] = airdata_dict['coValue']
    obj = MyModel.objects.create(kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM