2

models.py

class ModFile(models.Model):
    mod = models.ForeignKey(Mod, on_delete=models.CASCADE)
    title = models.CharField(max_length=128)
    downloads = models.IntegerField(default=0)
    file = models.FileField(upload_to='mods/')

views.py

class downloadMod(APIView):
    def get(self, request, id):
        file = models.ModFile.objects.get(id=id)
        file.downloads += 1
        file.save()
            
        return FileResponse(file.file)

In views.py, the get() function retrieves the model by its id and should increment file.downloads by 1 but for some reason it increments by 2, what am I doing wrong?

Lun
  • 861
  • 1
  • 10
  • 18
  • 2
    I am pretty sure `file.downloads += 1` isn't adding 2 instead of 1. I think you must be sending two `GET`s inadvertently. Try printing something to the console when `get()` is executed. – HuLu ViCa Aug 13 '21 at 20:48
  • nope, only 1 request gets sent :o – Lun Aug 13 '21 at 20:55
  • 2
    I agree, that it only adds one. Please try to print out file.downloads immediately before and immediately after the file.downloads += 1 maybe the start value is 1 or something else. – Frederick Aug 13 '21 at 21:07
  • If this is local, you can probably debug and print to see if get is really called just oncce – Brian Destura Aug 14 '21 at 01:33
  • This isn't really a problem in this specific case, but read [python - Race conditions in django - Stack Overflow](https://stackoverflow.com/questions/1030270/race-conditions-in-django#10987224) ------ Make sure that the server only receive 1 GET request. Something on the way from the client to the server may decide to make another request (HTTP to HTTPS redirection? Download manager? Browser prefetch? etc.) – user202729 Aug 14 '21 at 08:33

0 Answers0