9

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?

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Ashish Kumar Saxena
  • 4,400
  • 8
  • 27
  • 48

1 Answers1

11

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/

Arpit
  • 953
  • 7
  • 11
  • thank for your reply.. i want to access all fields data. i don't know column name since join query generating dynamically... – Ashish Kumar Saxena Dec 02 '13 at 10:06
  • You could use `tab._meta.fields` to get the list of all fields in the table. Iterate over them and use `getattr` method get values like this: `for f in obj._meta.fields: print getattr(obj, f)` – Arpit Dec 02 '13 at 12:20
  • 1
    I had a RawQuerySet object and needed to know how to retrieve values of attributes contained as collections within the object. This answer is exactly what I needed. I don't understand why it had been down-voted in the first place. – Lym Jul 27 '15 at 13:08