Django: Get() Returned More Than One Items -- It Returned 3
Solution 1:
just go through the django documentation https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#get-object-or-404
it internally calls get() https://docs.djangoproject.com/en/2.0/ref/models/querysets/#django.db.models.query.QuerySet.get
it will raise MultipleObjectsReturned if more than one object was found.
you need to either pass primary_key or any other fild to get_object_or_404 like:get_object_or_404(MyModel, pk=1)
or you can use filter() if you want multiple records.
Solution 2:
As other answers have pointed out, you need to filter the queryset in get_object_or_404
so that it only returns a single object. However the next question is how do you know which object to fetch?
The usual approach for edit pages is to include the primary key or a unique slug in the url pattern:
path('edit_purchase/<int:pk>/', views.edit_purchase, name='edit_purchase'),
You then need to update the view to accept the new argument, and use it in get_object_or_404
.
def edit_purchase(request, pk):
entry =get_object_or_404(Purchases, pk=pk)
Finally, you need to include the argument when you reverse the URL, e.g.
{% url 'geo_gas:edit_purchase' entry.pk %}
Solution 3:
You need to provide arguments to get_object_or_404
not just model.
Take a look at source code of get_object_or_404
:
defget_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
"""
Also consider naming your Purchases
model as Purchase
to follow single naming convention.
Solution 4:
fixed purchase function for editing - correction
def edit_purchase(request):
""Edit an existing purchase record."""
entry = get_object_or_404(Purchases, pk=1)
#entry = Purchases.objects.filter(pk='date_added')#purchase = entry.purchaseif request.method != 'POST':
# Initial request; pre-fill form with the current entry
form = PurchasesForm(instance=entry)
else:
# POST data submitted; process data.
form = PurchasesForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('geo_gas:purchases'))
context = {'entry': entry, 'form': form}
return render(request, 'geo_gas/edit_purchase.html', context)
Post a Comment for "Django: Get() Returned More Than One Items -- It Returned 3"