Django: get_object_or_404 is not the right solution, but what is it?

I am struggling to work out the right solution for what I am trying to do here, and I will be very grateful for the help.

Right now I have a working system that takes "Special" from db and displays it in a browser. The user can edit this "Special" in the browser and send it to db. This change is displayed to the user.

The problem is that "Special" will not be updated if a pre-existing "Special" does not exist in db. In my views.py, I have:

def changeSpecialOffer(theRequest):
    myProductUuid = theRequest.POST['myProductUuid']
    myNewSpecialOffer = theRequest.POST['myNewSpecialOffer']
    myProduct = get_object_or_404(Product, uuid=myProductUuid)
    myActiveSpecial = get_object_or_404(SpecialOffer.objects.filter(product=myProduct).filter(
                                                            active=True))
    try:
        myActiveSpecial.special = myNewSpecialOffer
        myActiveSpecial.save()
    except:
        return HttpResponse(myActiveSpecial, mimetype='text/plain')
    myActiveSpecial = SpecialOffer.objects.filter(product=myProduct).filter(
                                                            active=True)
    return HttpResponse(myActiveSpecial, mimetype='text/plain')

I know that the reason why the Special update does not work is because it get_object_or_404correctly returns a 404 error, since there is no previously existing Special in db.

- , , db "Special" .

get_object_or_404 try except, , 'unicode' has no attribute 'save()'.

+5
2

:

myActiveSpecial = get_object_or_404(SpecialOffer.objects.filter(product=myProduct).filter(
                                                    active=True))

:

myActiveSpecial, just_created = SpecialOffer.objects.get_or_create(product=myProduct, active=True)

- :

try:
    myActiveSpecial = SpecialOffer.objects.get(product=myProduct, active=True)
except SpecialOffer.DoesNotExist:
    myActiveSpecial = SpecialOffer.objects.create(product=myProduct, active=True, ...something.more...)

- .

EDIT:

... HttpResponse. , , HttpResponse. , . __unicode__ .

- myActiveSpecial return? , .

+3

get_object_or_404 , , . , SpecialOffer.objects.get(), , , 404.

, .

:

myProduct = get_object_or_404(Product, uuid=myProductUuid) # this is correct
myActiveSpecial = SpecialOffer.objects.filter(product=myProduct).filter(active=True))

if myActiveSpecial.count():
  # There is one or more active specials!
else:
  # There are no active specials for this product

( , ).

myActiveSpecial = myProduct.specialoffer_set.filter(active=True)
0

All Articles