I'm using mysql with django 1.3 and I have posts stored in a database. The posts are stored for a certain amount of time, say 7 days. How can I delete a post when the duration(7 days) is up? I'm not asking how to delete, but more how to determine when to delete?
I don't know if this is a good way of doing things, but one way I'm considering doing this is when the user looks up a post(query sent) and the duration is 开发者_JAVA百科up, the post is deleted. Also, when I do a search or browse and a list of posts if pulled from the database, I'll go through the list and delete the posts over the time limit. What worries me about this implementation is when I pull a list, say ten posts, and 9 are over the time limit, I would have to get another list, and if there are posts over the limit in that list, I would have to get more .... etc. So one query could lead to a lot of queries and ultimately be very inefficient. So is there a better way to do this?
Or maybe a whole better way of implementing this?
So basically, how can I implement a system so that a user will never see a post that is past its duration?
Not sure if I worded everything correctly, I'm really confused on how to do this efficiently.
You'll probably want to set up a scheduled job to batch-delete old posts each night. Setting up a scheduled job that runs in the Django environment is covered in this post.
The top answer:
One solution that I have employed is to do this:
1) Create a custom management command, e.g.
python manage.py my_cool_command
2) Use cron to run my command at the required times.
Can't you mark a date of expiry on the post?
class Post(models.Model):
# ...
date_expire = models.DateField()
I would then extend the save method to add 7 days to the current date and save it to that field. Then when a user is retrieving the posts,
def some_view(request):
# ....
posts = Post.objects.filter(date_expire__gte=date_obj)
If you need to delete them, a simple way would be for the view to collect the expired post via a similar QuerySet and call delete(). Alternatively, you can also setup a script to run via cron for that kind of purposes.
You should use a daily cron job with a simple SQL DELETE by timestamp or a custom django management command.
Reference:
Custom django commands
Using contrab with django
精彩评论