0

Given the following model:

class Team(models.Model):
    name = models.CharField(max_length=50)
    others = DictField()

And the following code:

bahia = Team()
bahia.name = "E.C. Bahia"
bahia.others = {"title": "Ninguém nos Vence em Vibração!!!"}
bahia.save()

vicetoria = Team()
vicetoria.name = "E.C. Vicetoria"
vicetoria.others = {"title": "Vice de tudo!"}
vicetoria.save()

I want to find the object that have the word vence, (case insensitive) contained in title value of the field others.

I tried something like:

teams = Team.objects.filter(others__title__icontains="vence")

that gives me the following error:

FieldError: Join on field 'others' not permitted. Did you misspell 'title' for the lookup type?

I also already tried:

teams = Team.objects.filter(others__icontains={"title":"vence"})

that returns None and I know there is at least one collection as result.

SOLUTION:

teams = Team.objects.raw_query({"others.title": {"$regex" : "vence", "$options": "i"}})

The i option makes the search insensitive.

Paulo Fabrício
  • 319
  • 3
  • 17
  • Where are you getting DictField from? Are you trying to use a serialiser field from django rest framework in a Model object? – Asher Dec 04 '17 at 21:57
  • I created the DictField. It's being saved normally in the database. I am using MongoDB. – Paulo Fabrício Dec 04 '17 at 23:26
  • Can you show me what your DictField() looks like? – Asher Dec 04 '17 at 23:30
  • Hey, @Asher! It's there. In the example. bahia.others and vicetoria.others are the DictFields – Paulo Fabrício Dec 04 '17 at 23:41
  • I understand your example. I suspect that the issue your having is to do with using a custom model field in your models. What I'm wondering is what the DictField class looks like? How have you created your own field class? Are you inheriting from another class? – Asher Dec 04 '17 at 23:51
  • Ah! Ok. It's not another class. It's a field that varies. Each object can have its own dict with different keys from each other. – Paulo Fabrício Dec 04 '17 at 23:55
  • Can you show me your import statements from the top of your models.py file? – Asher Dec 04 '17 at 23:56
  • For sure: from djangotoolbox.fields import ListField, EmbeddedModelField, DictField – Paulo Fabrício Dec 04 '17 at 23:59

1 Answers1

0

I believe (correct me if I'm wrong) that djangotoolbox DictField doesn't support icontain.

To filter the Dict Field you need to do something like:

Team.objects.raw_query({'title': { $regex : /vence/i } })

Check out this answer: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine?

This answer shows how to do case insensitive mongodb queries: How do I make case-insensitive queries on Mongodb?

Asher
  • 677
  • 5
  • 10