Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrive values form RawQuerySet in django?

my input query is

query = "select * from tab1 left join tab2 on tab2.patient_id =tab1.patient_id ,tab3 left join tab4 on tab4.patient_id =tab3.patient_id"

data = model_name.objects.raw(query)

How do you retrieve values from a RawQuerySet?

like image 289
Ashish Kumar Saxena Avatar asked Dec 02 '13 09:12

Ashish Kumar Saxena


People also ask

How can I get raw SQL query in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


1 Answers

The result obtained by making raw queries using raw method of Manager generates instances similar to instances generated using get or filter method. To get a field simply do obj_name.attr.
For eg:

class Tab(models.Model):
    field1 = models.BooleanField()
    field2 = models.PositiveIntegerField()

query = "select * from app_name_tab"
objs = Tab.objects.raw(query)
for obj in objs:
    print obj.field1, obj.field2

For more info, refer to https://docs.djangoproject.com/en/dev/topics/db/sql/

like image 198
Arpit Avatar answered Sep 18 '22 12:09

Arpit