Wednesday, October 30, 2013

Dynamic query with Foreign Key

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__?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/028ab892-1f80-4dcf-9972-24dca90ffc5c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment