Q: List of dict access with mongoengine in django

Viewed 1248

how to get particular dictionary from the list of dictionaries using mongoengine in django. As specified below data structure if I want to fetch the dictionary having the student_id as "1011". how to do and how to update that dictionary only one?

Data structure like that :

class studentData(Document):
    student_class = StringField(required=True)
    student_list = ListField()

Data store in DB sample:

{
    "student_class":10.
    "student_list":[
        {
            "student_id" : "1011",
            "student_name" : "ABC"
        },
        {
            "student_id" : "1045",
            "student_name" : "XYZ"
        }
    ]
}

I am try this is give me student_list but how to I get list of specific dictionary :

studen_list= studentData.objects.filter(student_class=10).values_list('student_list')[0]
1 Answers

why don't you write a custom manager for this purpose?

class studentData(Document):
    student_class = StringField(required=True)
    student_list = ListField()

    find_inside_student_list = FindInsideStudentManager()

class DahlBookManager(models.Manager):
    def get_queryset(self, student_id):
        for data in super().get_queryset():
            if student_id == data['student_id']:
                return data

student_details= studentData.objects.find_inside_student_list.filter(student_class=10, student_id='1011')

P.S. : The above code might not work due to some syntax issue. I have written this code only to give an idea how you can implement it

UPDATE: I found another approach which uses the native mongoengine.

class Model(mongoengine.Document):
    student_list = mongoengine.ListField(mongoengine.ReferenceField(StudentDetailsModel))

class StudentDetailsModel(mongoengine.Document):
    student_id = mongoengine.StringField()
    student_name = mongoengine.StringField()



Model.objects.filter(student_id__contains='1011')

You can read more about it here

Related