1

I am using Django with MongoDB as my database. I create a model (MyObject) and one field is an ArrayField type that contains in which entry JSON Fields. For that I created an abstract model.

So my models.py:

class MyObject(models.Model):
    ...
    myArrayField = models.ArrayField(model_container=NIC, null=True, blank=True, default=[])
    ...

class MyAbstractObject(models.Model):
    field1 = models.CharField(null=True, blank=True, max_length=100, default="")
    field2 = models.IPAddressField(blank=True, null=True, default="")
    
    class Meta:
        abstract = True

In mongoDB I have:

MyObject:
{
   ...
   myArrayField: [{field1: "abc", field2: "1.1.1.1"}]
   ...
}

Now I want to get the element that have the value "1.1.1.1", how can I do that?

I try:

q1 = MyObject.objects.filter(myArrayField__contains='1.1.1.1')
q2 = MyObject.objects.filter(myArrayField_0_field2='1.1.1.1')
q3 = MyObject.objects.filter(myArrayField__contains={'field2':'1.1.1.1})

Can you help me?

1 Answer 1

1

The Djongo Doc makes querying an ArrayField very clear, here's an example from the doc:

entries = Entry.objects.filter(authors={'name': 'Paul'})

which in your case will be something like:

q1 = MyObject.objects.filter(myArrayField={'field2'='1.1.1.1'})

take a look at the doc for more complex querying

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

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.