0

I am building an advance search in django/angular where user can select one or more fields from different models

#############               #############           #############
Model1                      Model2                  Model2
#############               #############           #############   
Field1                      Field1                  Field1
Field2                      Field2                  Field2
Field3                      Field3                  Field3
......                      Fk(Model1)              Fk(Model1)
                            .......                 ..........

Model2, Model3 and other models have foreignkey reference to Model1.

The selected models fields are send to the django views for further queries and result concatenation.

views.py

def customsearch(request):
    queryrequest = json.loads(request.body)

    result = []
    print queryrequest
    """ [{u'value': u'Field1', u'key': u'Model1'}, {u'value': u'Field2', u'key': u'Model2'}, {u'value': u'Field3', u'key': u'Model2'}, {u'value': u'Field2', u'key': u'Field2'}]"""

    for item in queryrequest:
        if(item['key'] == 'Model1'):
            result.append(Model1.objects.filter().values(item['value']))
        else:
            result.append(item['key'].objects.filter().values(item['value']).select_related('fk'))

I have got a request of list of dictionaries. The list consist of key (model name) and value (field).

How can i make a queries and contenate results based on above example?

I am newbie to django!

Any helps and suggestions are welcome.

MysticCodes
  • 3,092
  • 5
  • 25
  • 33

1 Answers1

2

if your model2, model3 has fk to model1,

this is sample (you should use related_name for Model2, Model3 ForeignKey Field)

from django.db.models import Q
Model1.objects.filter(
    Q(Field1=value1) & 
    Q(model2_related_name__Field2=value2) &
    Q(model3_related_name__Field3=value3)
)

and, about related_name this

beCurious
  • 152
  • 7
  • Can I `Model1.objects.filter()`? And i don't want to match field with value instead get all results. I have edited `views`. – MysticCodes Apr 26 '16 at 11:41
  • if you want get all results, not filter(), use all(). – beCurious Apr 26 '16 at 15:43
  • and i cannot understand waht you want this code. result.append(item['key'].objects.filter().values(item['value']).select_related('fk'))' – beCurious Apr 26 '16 at 15:44
  • and if you want to get Model Class by string. see this [link](http://stackoverflow.com/questions/4881607/django-get-model-from-string) – beCurious Apr 26 '16 at 15:46