1

I want to get only one value (for example, one "cantidad", BUT ONLY ONE, even if there are repeated values).

This is my model:

from django.db import models
from django.utils import timezone

class Data(models.Model):

    palabra = models.CharField(max_length=200)
    cantidad = models.IntegerField()
    fecha = models.DateTimeField(
                default=timezone.now)

    def returnFecha(self):
        return self.fecha

    def __str__(self):
        return self.palabra , self.cantidad , self.fecha

Taking into account that I have already filled the table/db with data, I have tried this:

q1=Data.objects.get(cantidad=56).first()

But this gets me this error:

get() returned more than one Data -- it returned 7!

Why? Having first() should not cause any problems.

1
  • 1
    Well get(..) retrieved a only a single item. You should use first() if you filter. Jun 5, 2018 at 13:18

2 Answers 2

1

You have to write:

q1 = Data.objects.filter(cantidad=56).first()

It returns the first object from your list object with cantidad=56.

1

get

Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get returns a single object, not query-set. That's why we can't use first() after get.

filter

Returns a new QuerySet containing objects that match the given lookup parameters.

filter returns query-set. You can use first() after filter

You need to use filter and then first(),

Data.objects.filter(cantidad=56).first()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.