How to delete a certain model instance in django after a given date

961 views
Skip to first unread message

YOGITHA A N

unread,
Nov 5, 2016, 2:31:20 PM11/5/16
to Django users
So  here are my models:

     class Mess(models.Model):
    muser = models.OneToOneField(User)
    MESS_NAME = (('GH','girls hostel top mess'),
                    ('IH','girls hostel down mess'),
                    ('MM','Mega mess'),
                    ('FB','First Block mess'),
                    ('SB','Second Block mess'),
                    ('TB','Third Block mess'),
                    )
    mess_name = models.CharField(max_length=25, choices = MESS_NAME,primary_key=True)
    per_day_cost = models.IntegerField()
    def __str__(self):
        return self.mess_name

class MessMenu(models.Model):

    mess_name = models.ForeignKey(Mess)
    day = models.DateField()
    morning = models.TextField()
    afternoon = models.TextField()
    snacks = models.TextField()
    dinner = models.TextField()
    def __str__(self):
        return self.mess_name

Once i create an object in MessMenu I want django to delete that object after 7 days. Please let me know how to delete a certain object after a given period of time.

Vijay Khemlani

unread,
Nov 5, 2016, 8:24:56 PM11/5/16
to django...@googlegroups.com
You could write a management command


and execute it regularly (for example using a cron job)

--
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...@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/6dcf1a57-7a89-40e1-b6e7-fbd28e78c27d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

王安刚

unread,
Nov 5, 2016, 11:51:27 PM11/5/16
to Django users
i think maybe you need a schedule job to delete the model.
you can mark the model with a ctime, and check whether any model with ctime 7 days from now and then delete it.

在 2016年11月6日星期日 UTC+8上午2:31:20,YOGITHA A N写道:

YOGITHA A N

unread,
Nov 6, 2016, 7:51:45 AM11/6/16
to Django users
menudeleted = MessMenu.objects.filter( day__lt = timezone.now())
    for m in menudeleted:
        m.delete()
menu = MessMenu.objects.all()

use basic comparison filter to filter the dates

Reply all
Reply to author
Forward
0 new messages