Huzaifa Zahoor
Huzaifa Zahoor

Reputation: 335

Update Object not Duplicate in views.py django

this is my code

def createstock(request):
    stock = Stock()
    stock.title = 'AAPL'
    stock.div_ammount = '1'
    stock.save()
    return render(request, 'stocks/index.html')

Whenever i call this this via URL. It creates the row in the database table. But i want to check that if

stock.title = 'AAPL'

this title is already in database then dont create object, only update its values. These values will be dynamic in future. But now its hardcore values.

Upvotes: 0

Views: 136

Answers (2)

Sergey Pugach
Sergey Pugach

Reputation: 5669

def createstock(request):
    stock, created = Stock.objects.update_or_create(title="AAPL", defaults={"div_ammount": "1"})
    return render(request, 'stocks/index.html')

Upvotes: 2

sdarmofal
sdarmofal

Reputation: 41

You are looking for update_or_create:

Upvotes: 3

Related Questions