Compare objects list and get a list of object to inserted or updated
**Problem** You have an input `json` with which you will create a list of objects, you have to validate that the object will be created if it not exists, if exists determine whether to upgrade or discard depending of they have not undergone any changes. Solution 1) With the input `json` will be created the list of objects of the class that we insert or updatee 2) Read all fields in the database, using one of the fields as key to creating a dictionary with the objects in the database 3) Compare the objects and determine if it will be updated, inserted or discarded Django problem: by default only compares the level objects using the primary key (id). Compare field by field is the solution to determine if the object has changed. hints: The _state field is present in every object, and it will produce a random memory location, You can find cache fields so you need to remove these begins with underscore `_`. The fields excluded can be fk, and these fields produce field_id, so you will needs to exclude it class Country(models.Model): # country code 'MX' -> Mexico code = models.CharField(max_length=2) name = models.CharField(max_length=15) class Client(models.Model): # id=1, name=pedro, country.code=MX, rfc=12345 name = models.CharField(max_length=100) country = models.ForeignKey(Country) rfc = models.CharField(max_length=13) Country.objects.create(**{'code': 'MX', 'name': 'Mexico'}) # creating the country Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) # creating the client obj_db = Client.objects.get(id=1) country = Country.objects.get(code='MX') obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) obj_db == obj_no_db # True obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':1}) obj_db == obj_no_db # True # but isn't True because the rfc has change, how can compare field by field obj_db.rfc == obj_no_db.rfc # False, I was expected this result when compare obj_db == obj_no_db because they are not equal **Solution to compare field by field** _obj_1 = [(k,v) for k,v in obj_db.__dict__.items() if k != '_state'] _obj_2 = [(k,v) for k,v in obj_no_db.__dict__.items() if k != '_state'] _obj_1 == _obj_2 # False This is only for one object, and you can include in `__eq__` method in your model, but what happen if you need compare a list of object to bulk for insert or update with `django-bulk-update`. Well my snipped pretends solve that. so **How can use it.** obj_list = [<Object Client>, <Object Client>, <Object Client>, <Object Client>] get_insert_update(Client, 'id', obj_list) exclude_fields = ['country'] get_insert_update(Client, 'id', obj_list, exclude_fields=exclude_fields)
- models
- bulk