1

I have a weird problem, I think it comes from the cache between django and postgres but not so sure.

I have multiple tables in database but the problem only happens with one of them. Let's say the SpeakingSession table. Everytime I make a change like add a new instance, edit an instance, the call api request does not return the change; the data is only updated when I restart the apache2 server.

For example: I have 7 SpeakingSession records, then I add a new one. But the print command below returns 7.

class SpeakingSessionViewSet(viewsets.ModelViewSet):

    queryset = SpeakingSession.objects.all()

    def list(self, request):
        print(self.queryset.count())
        return super(SpeakingSessionViewSet, self).list(request)

So I restart the apache2 server, then it returns 8.

Any idea how to fix this problem? Thank you very much!

This is my model and my serializer:

class SpeakingSession(models.Model):

    sessionDefinition = models.ForeignKey('SessionDefinition', on_delete=models.CASCADE)
    startTime = models.TimeField()
    endTime = models.TimeField()
    participants = models.ManyToManyField('Profile', default=None, blank=True)

class SpeakingSessionSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpeakingSession
        fields = ('id', 'sessionDefinition', 'startTime', 'endTime', 'participants')
Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Trong Lam Phan
  • 2,292
  • 3
  • 24
  • 51

1 Answers1

0

Try using Model.refresh_from_db

If you need to reload a model’s values from the database, you can use the refresh_from_db() method. When this method is called without arguments the following is done:

All non-deferred fields of the model are updated to the values currently present in the database. Any cached relations are cleared from the reloaded instance.

https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.refresh_from_db

Ben
  • 2,348
  • 1
  • 20
  • 23