[Answer]-Django remove least recent many to many entry

1👍

Take a look at the documentation on Querysets for details of how to do this. You can use order_by to order your objects by date, and use Python’s array slicing syntax to limit the number of results.

An example of showing the most recently added items in your view might look something like this:

viewed = Profile.objects.order_by("-date_added")[:25]

This doesn’t delete everything after 25 – it just fetches the 25 most recent objects (assuming your Profile model has a field called date_added).

EDIT: Oops, I think I misread your question.

I think what you’d need to do is have an intermediate model – Django allows you to use a third model as an intermediate one between two different models in a many-to-many relationship. Then you could add the time viewed to that model and store it that way. There’s a good example in the documentation.

I wouldn’t really bother deleting the old ones unless database space was likely to be an issue, but if you need to for any reason, I guess you could set up a signal that was triggered by a new view being created and have that call a function that deletes all but the 25 most recent.

0👍

Django doesn’t track the date added for a ManyToMany relationship, so it’s not possible to do this reliably without adding a field. To achieve this you’ll need to do is add a date field on your ManyToMany intermediary table, then order by that – for example

class ProfileViewed(models.Model):
    viewed = models.ForeignKey('Profile')
    viewer = models.ForeignKey('Profile')
    date_added = models.DateField(auto_now_add=True)

class Profile(models.Model):
    ...
    viewed = models.ManyToManyField('self', null=True, blank=True, related_name='viewed_profiles', symmetrical=False, through=ProfileViewed)

Then you can order your results like so:

profile = Profile.objects.get(...)
views = ProfileViewed.objects.filter(viewed=profile).order_by('date_added')
👤Greg

Leave a comment