Home > Enterprise >  Is it possible to get a list of all deleted items in a django model without the use of safedelete or
Is it possible to get a list of all deleted items in a django model without the use of safedelete or

Time:04-06

I'd like to have a record for all deleted items presented to the user. I've used safedelete but I want to change.

My model

class Issue(SafeDeleteModel):
    _safedelete_policy = SOFT_DELETE
    borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
    book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
    issue_date = models.DateField(default=datetime.date.today)
    return_date = models.DateField()
    issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
    DAYS = [(str(a), str(a)) for a in range(1, 21)]
    due_days = models.IntegerField(default=7,validators=[MinValueValidator(1), MaxValueValidator(3650),])
            
    def save(self, *args, **kwargs):
        self.return_date = self.issue_date   datetime.timedelta(days=self.due_days)
        super(Issue, self).save(*args, **kwargs)
    
    class Meta:
        #unique_together = ('book_id','borrower_id'),
        indexes = [models.Index(fields=['book_id', ]),
                   models.Index(fields=['borrower_id', ]),
                   ]

    def __str__(self):
        return str(self.book_id)

CodePudding user response:

You can add a UniqueConstraint with a condition to only enforce it under certain conditions

class Issue(SafeDeleteModel):
    ...
    
    class Meta:
        ...
        constraints = [
            models.UniqueConstraint(fields=['book_id', 'borrower_id'], condition=Q(deleted__isnull=True), name='unique_book_id_borrower_id')
        ]

The package you are using seems fine for your use-case, the package django-simple-history seems to also track deleted objects and doesn't store the data in the same table, might be worth a look if you want to store deleted data somewhere else

  • Related