'Django conditional inserts in multiple fields

I have two Django model: Object and Purchases. On the Object model, there are two fields: date_most_recent_purchase and date_first_purchase. I am inserting many dictionnaries, and each dictionnary can have the following values (of course, the date and object_id can be any value):

{"object_id": 1, "date_purchase": None, "date_first_purchase": None}
{"object_id": 1, "date_purchase": None, "date_first_purchase": "2020-11-11"}
{"object_id": 1, "date_purchase": "2019-12-12", "date_first_purchase": None}
{"object_id": 1, "date_purchase": "2018-2-10", "date_first_purchase": "2018-2-2"}

Below are my Django models:

class Object(models.Model):
    object_id = models.IntegerField(unique=True)
    date_first_purchase = models.DateField(null=True)
    date_most_recent_purchase = models.DateField(null=True)


# this second model is not very important here
class Purchase(models.Model):
    purchase_id = models.IntegerField(unique=True)
    date_purchase = models.DateField(null=True)
    

(For a given object_id, I have many purchases)

I would like to define some rules:

  • if for a given object_id, there is no date_most_recent_purchase (= null) in DB, but a date_first_purchase in the dictionary (such as {"object_id": 1, "date_purchase": None, "date_first_purchase": "2020-11-11"}), we should set the value of date_first_purchase in DB for field date_most_recent_purchase.
  • We should apply the same logic in the other case: date_first_purchase is null in DB, and dictionary contains a value such as {"object_id": 1, "date_purchase": "2019-12-12", "date_first_purchase": None}
  • If date_first_purchase is set in DB, but the dictionary contains a value with a lower value of date_first_purchase, we should set the lower value
  • In the same way, if date_most_recent_purchase is set in DB, but file contains a value with a higher value of date_purchase, we should set the new value.

My question: What is the cleanest way with Django 3+ to manage all these rules ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source