MultipleObjectsReturned Django

0

I want to return the 2 or n records matches that appear but shows me the following exception

  

Exception Value:

     

get () returned more than one File - it returned 2!

The Query that returns the exception

queryModeloArchivo= Archivo.objects.get(modelo=query2Model, status=1)
queryArchivo= queryModeloArchivo.modelo

If I change the query to filter, with this I get all the records that is to say the 2 registers:

queryModeloArchivo= Archivo.objects.filter(modelo=query2Model, status=1)

However, I can no longer access the properties of the queryModelFile model, that is:

queryArchivo= queryModeloArchivo.modelo
    
asked by Noel L 27.03.2018 в 19:46
source

2 answers

1

That error is because the query that is used in the get method must return a single record no more. For example when we make queries by the id of the element.

For queries in the result is more than one record you should use the filter method of the queryset and not get.

From the documentation:

  

Django will complain if more than one item matches the   get () query. In this case, it will raise MultipleObjectsReturned,   which again is an attribute of the model class itself.

It basically says that when the query returns more than one object it throws the exception MultipleObjectsReturned

You must bear in mind that when you use the filter method you are obtaining a queryset and not the set of elements to obtain the elements you must evaluate the queryset either using a slice or the all method of django.

queryset = File.objects.filter (model = query2Model, status = 1)

objetos = queryset.all()

or

objetos = queryset[0:]

or

for obj in queryset:
    # codigo aqui.
  

QuerySets are lazy - the act of creating a QuerySet does not involve   any database activity. You can stack filters together all day long,   and Django will not actually run the query until the QuerySet is   evaluated.

    
answered by 27.03.2018 в 21:08
0

When you make a query with filter() you have to bear in mind that this returns everything you machea with your query in a list, therefore to access the properties of an object you must or cross it with

...
for query in queryModeloArchivo:
    // Entonces aqui preguntas por las propiedades de cada uno
    queryArchivo = query.modelo
...
    
answered by 28.03.2018 в 16:34