Peter
Peter

Reputation: 53

How can I update the database in Django?

I am building a web service and trying to update my db but obviously this is not the right method to do it. Can I have a helping hand here, I have tried all variations. I got this error: local variable 'Printer' referenced before assignment. I tried to change the name to PrinterObj but then I got the error: PrinterObj have no save method. What I want to do is to save to a new record if it is not existing and if it exist I want to update. I thought it should be simple.

from .models import Printer

class RequestData(APIView):
  permission_classes = (IsAuthenticated,)

  def get(self, request):
    Printer = Printer.objects.get(printername = printername)
    if Printer: #UPDATE
        Printer.printername = printername
        Printer.ip = request.META['REMOTE_ADDR']
        Printer.lastupdate = datetime.now()
        Printer.save()
    else: #CREATE
        b = Printer(
            printername = printername, 
            ip = request.META['REMOTE_ADDR'],
            lastupdate = datetime.now()
        )
        b.save()

Upvotes: 1

Views: 28

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The reason this happens is because you specify Printer = …, hence Printer is a local variable, and to make matters worse, you used Printer at the right part of the expression, so it is used before you assign it.

The solution is to give the object a different name than the class. Therefore in Python local variables are often written in lowercase.

It will furthermore error on the fact that .get() raises an error if it can not find the object. You can use .first(..) or even better, use update_or_create(..):

class RequestData(APIView):
  permission_classes = (IsAuthenticated,)

  def get(self, request):
    Printer.objects.update_or_create(
        printername=printername,
        defaults={
            'ip': request.META['REMOTE_ADDR'],
            'lastupdate': datetime.now()
        }
    )
    return …

You still need to return a HTTP response, for example JsonResponse({'success': true}). Furthermore a GET request is not supposed to have side effects, so perhaps it is not a good idea to create or update objects with def get(...).

Upvotes: 1

Related Questions