Hi,

Can somebody explain me the reason why model save() method doesn't respect database settings?

I have case with foreign key defined like this:

class Measurements(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, *blank=True, null=True*)     order = models.ForeignKey(Order, on_delete=models.SET_NULL, *blank=True, null=True*)

Also Customer model itself has foreign key to Measurements:

class Customer(models.Model):
    measurements = models.ForeignKey(Measurements, on_delete=models.CASCADE)

I need this hack to create model form set for a customer. Measurements must have foreign key to it for this to work. But unfortunately save method doesn't respect my settings. It force me to assign customer to measurements where customer itself cannot be created because it requires measurements. The thing is i don't really care about connection from measurements side. This is the reason why it allowed to be null.

So, for now i just override save() method for Measurements model and add check for the null attribute. Like this:

if *field.null is not True* and obj and obj.pk is None:
     # Remove the object from a related instance cache.
     if not field.remote_field.multiple:
       field.remote_field.delete_cached_value(obj)
     raise ValueError("save() prohibited to prevent data loss due to unsaved related object '%s'." % field.name)

As you can see Measurements model has two such foreign keys. Where Customer and Order must take leading part in pairs. There are cases where i want keep "orphan" measurements. And looks like this is valid case as soon as save() will start respect field settings.

Thank you in advice,

Roman


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a82fc6ed-5d8f-b24b-2d9c-da59639a6af8%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to