Home > database >  How to delete data after fetch in a same action in Django?
How to delete data after fetch in a same action in Django?

Time:07-25

I have a table in DB named Plan. see code in models.py:

class Plan(models.Model):
    id = models.AutoField(primary_key=True)
    Comments = models.CharField(max_length=255)
    def __str__(self):
        return self.Comments

I want to fetch data(comments) from DB and after that data will be deleted. That means one data will be fetched once. And this data will be shown in the Django template. I tried, see views.py

def Data(request):
    data =  Plan.objects.filter(id=6)
    # latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first()
    # Plan.objects.all()[:1].delete()    
    context = {'data':data}
    dataD =  Plan.objects.filter(id=6)
    dataD.delete()
    return render(request,'data.html',context)

this code is deleting data from DB but not showing in the template. How can i do this?

CodePudding user response:

Your template must be updated because it fetch the data from the db one time only so if db is updated your template wouldn't change

CodePudding user response:

From django docs:

Pickling QuerySets¶

If you pickle a QuerySet, this will force all the results to be loaded into memory prior to pickling. Pickling is usually used as a precursor to caching and when the cached queryset is reloaded, you want the results to already be present and ready for use (reading from the database can take some time, defeating the purpose of caching). This means that when you unpickle a QuerySet, it contains the results at the moment it was pickled, rather than the results that are currently in the database.

If you only want to pickle the necessary information to recreate the QuerySet from the database at a later time, pickle the query attribute of the QuerySet. You can then recreate the original QuerySet (without any results loaded) using some code like this:


>>> import pickle
>>> query = pickle.loads(s)     # Assuming 's' is the pickled string.
>>> qs = MyModel.objects.all()
>>> qs.query = query            # Restore the original 'query'.

  • Related