Tuesday, April 26, 2016

Re: Django apparently can't handle that error.

On Tue, Apr 26, 2016 at 08:17:40PM +0200, Michal Petrucha wrote:
> Have you considered altering the table for Log to include an ON DELETE
> CASCADE clause instead? That would make the error go away without too
> much effort, even though I still think the behavior you are
> implementing is simply incorrect.

Doh, there might be an even easier solution:

class Account(models.Model):
marked_for_delete = models.BooleanField(default=False)

def delete(self):
with transaction.atomic():
self.marked_for_delete = True
self.save()
super().delete()


class Car(models.Model):
account = models.ForeignKey('Account', on_delete=models.CASCADE)


class Log(models.Model):
account = models.ForeignKey('Account', on_delete=models.CASCADE)


class CarLog(Log):
car = models.ForeignKey('Car', null=True, blank=True, on_delete=models.SET_NULL)


@receiver(post_delete, sender=Car):
def create_car_log(sender, instance, **kwargs):
if not instance.account.marked_for_delete:
CarLog.objects.create(
account=instance.account,
)


Maybe, if it is guaranteed that during a delete operation, the same
instance of Account is used even when accessed from related objects,
you might be able to leave out the BooleanField, and just set an
attribute instead, but I'm not sure at the moment, so I'll leave it to
you to figure that part out.

Michal

--
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+unsubscribe@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/20160426193051.GU435%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment