4

I am using Django, with mongoengine. I have a model Classes with an inscriptions list, And I want to get the docs that have an id in that list.

classes = Classes.objects.filter(inscriptions__contains=request.data['inscription'])

3 Answers 3

10

Here's a general explanation of querying ArrayField membership:

Per the Django ArrayField docs, the __contains operator checks if a provided array is a subset of the values in the ArrayField.

So, to filter on whether an ArrayField contains the value "foo", you pass in a length 1 array containing the value you're looking for, like this:

# matches rows where myarrayfield is something like ['foo','bar']
Customer.objects.filter(myarrayfield__contains=['foo'])

The Django ORM produces the @> postgres operator, as you can see by printing the query:

print Customer.objects.filter(myarrayfield__contains=['foo']).only('pk').query
>>> SELECT "website_customer"."id" FROM "website_customer" WHERE "website_customer"."myarrayfield_" @> ['foo']::varchar(100)[]

If you provide something other than an array, you'll get a cryptic error like DataError: malformed array literal: "foo" DETAIL: Array value must start with "{" or dimension information.

Sign up to request clarification or add additional context in comments.

Comments

3

Perhaps I'm missing something...but it seems that you should be using .filter():

classes = Classes.objects.filter(inscriptions__contains=request.data['inscription'])

1 Comment

In fact it is working, didn't taught it work on arrays too. Thanks. What is the difference between filter and the way I did ?
1

This answer is in reference to your comment for rnevius answer

In Django ORM whenever you make a Database call using ORM, it will generally return either a QuerySet or an object of the model if using get() / number if you are using count() ect., depending on the functions that you are using which return other than a queryset.

The result from a Queryset function can be used to implement further more refinement, like if you like to perform a order() or collecting only distinct() etc. Queryset are lazy which means it only hits the database when they are actually used not when they are assigned. You can find more information about them here.

Where as the functions that doesn't return queryset cannot implement such things.

Take time and go through the Queryset Documentation more in depth explanation with examples are provided. It is useful to understand the behavior to make your application more efficient.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.