Y
Y
Yura Khlyan2019-10-09 16:16:20
Django
Yura Khlyan, 2019-10-09 16:16:20

What is the correct way to use queryset.delete()?

Good day.
I have the following models:

class Account(models.Model):
    user = models.ForeignKey(
        'users.User', on_delete=models.CASCADE, related_name='accounts'
    )
    balance = models.DecimalField(decimal_places=2, max_digits=22)
    currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES)

    def __str__(self):
        return f'<Account {self.user.email} ({self.currency.upper()})({self.pk})>'


class Transaction(models.Model):
    transaction_type = models.CharField(max_length=16, choices=TRANSACTION_TYPE_CHOICES)
    amount = models.DecimalField(decimal_places=2, max_digits=22)
    currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES)
    account_receiver = models.ForeignKey(
        'accounts.Account', on_delete=models.CASCADE,
        related_name='transactions_received'
    )
    account_sender = models.ForeignKey(
        'accounts.Account', on_delete=models.SET_NULL,
        related_name='transactions_send', blank=True, null=True,
    )

    def __str__(self):
        return f'<Transaction {self.transaction_type}({self.pk})>'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        TransactionHelper(transaction=self).apply_transaction()

    def delete(self, *args, **kwargs):
        super().delete(*args, **kwargs)
        TransactionHelper(transaction=self).revert_transaction()

As you can see, there is an account, and transactions to it. When I create a transaction, I apply it to the account, and when I delete it, I roll it back. Everything works fine when you delete it from the admin panel from the transaction details page. But when to delete from the list, it does not work, so the deletemodel method is not called there.
I found that deletion occurs through a method delete_querysetin ModelAdmin. Here he is:
def delete_queryset(self, request, queryset):
    """Given a queryset, delete it from the database."""
    queryset.delete()

How can I better and more correctly roll back transactions in this case?
1. First run through everything querysetand roll back all transactions, then delete queryset? But what if, for some reason, the deletion was not successful: not all records were deleted, nothing was deleted, and so on?
2. Iterate over queryset-y and roll back transactions one by one, deleting them?
3. What are your suggestions?
Thank you

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question