Dynamic query with Foreign Key

18 views
Skip to first unread message

Domagoj Kovač

unread,
Oct 30, 2013, 11:16:05 AM10/30/13
to django...@googlegroups.com
Hi guys,

I have a question. I have a a code like this: 

where model_object is an instance of an Model.

        for field in model_object._meta.fields:
            field_type = type(field)
            if field_type is not AutoField and \
                            field.name != "created" and \
                            field.name != "created_by" and \
                            field.name != "modified" and \
                            field.name != "modified_by" and \
                            field.name != "deleted" and \
                            field.name != "deleted_by":
                q = None
                if field_type is CharField:
                    q = Q(**{"%s__contains" % field.name: search_term })
                elif field_type is ForeignKey:
                    q = Q(**{"%s__name__contains" % field.name: search_term })

                if q:
                    if query:
                        query = query | q
                    else:
                        query = q

        rows_list = rows_list.filter(query)


I would like to create a function that i can use for searching trough database. The problem is that i want to be able to search trough Foreign Key fields. Models have __unicode__, is there any way that i could search trough the value defined in __unicode__?
Reply all
Reply to author
Forward
0 new messages