Pypix
Pypix

Reputation: 71

Django - Keep latest record of User

I want to keep the latest record of a user:

class Record(models.Model):
    name        = models.ForeignKey(User, on_delete=models.CASCADE)
    image       = models.ImageField(default='default.jpg', upload_to='site_pics')
    date        = models.DateTimeField(null=True, blank=True, auto_now_add=True)

    def save(self, *args, **kwargs):
        super(Record, self).save(*args, **kwargs)
        numdata = Record.objects.select_related('name').count()
        print(numdata)
        #if numdata > 1:
        #    Record.objects.select_related('name').first().delete()

As per this post Filter latest record in Django, I tried:

None of them return the correct number of records or don't work at all because I'm using SQLite.

Thank you for any suggestions

Upvotes: 1

Views: 37

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

In that case it might be better to change the modeling to a OneToOneField, such that the database will reject a second Record for the same user. You might also want to change the name of the relation to user, since you are referring to a user object, not its name.

In the save(…) method, you can look if the primary key is not yet filled in, if that is the case, you can delete the original record of the user. Regardless whether that exists or not. If this records does not exist, then it will act as no-op, where nothing changes in the database:

class Record(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='site_pics')
    date = models.DateTimeField(null=True, blank=True, auto_now_add=True)

    def save(self, *args, force_insert=False, **kwargs):
        if self.pk is None or force_insert:
            Record.objects.filter(user_id=self.user_id).delete()
        return super().save(*args, force_insert=force_insert, **kwargs)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 1

Related Questions