How to use Database Views in Django Rest Framework

705 views
Skip to first unread message

Shoaib Ijaz

unread,
Apr 18, 2014, 3:19:51 AM4/18/14
to django-res...@googlegroups.com

I am using Django Rest Framework for serialize data. I came across a scenario where I have to use Database Views as Model.

My Model

class A(models.Model):
    name = models.CharField(max_length=240, blank=True)
    value = models.CharField(max_length=240, blank=True)

    class Meta:
        db_table = 'tbl_a'

class B(models.Model):
   name = models.CharField(max_length=240, blank=True)
   value = models.CharField(max_length=240, blank=True)

    class Meta:
        db_table = 'tbl_b'

Database View Query

CREATE OR REPLACE VIEW ab_view AS
SELECT id,name,value FROM tabl_a WHERE name='foo' UNION (SELECT b.id,b.name,b.value FROM tabl_b b WHERE b.name='foo')

Model For Database View

class ABView(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=240, blank=True)
    value = models.CharField(max_length=240, blank=True)

    class Meta:
        db_table = u'ab_view'
        managed = False

Print Text Query

query = ABView.objects.all()
print query.count() #output (1000)

When I used ABView as Model in serializer class in it shows me error

TypeError at /ViewName/ 'source' is an invalid keyword argument for this function

class ABViewSerializer(rest_serializer.Serializer):

    class Meta:
        model = AbView
        fields = ('name', 'value')

View

class ABViewSet(viewsets.ModelViewSet):
    serializer_class = ABSerializer
    queryset = ABView.objects.all()

Is there anything missing in this code?

Can I use Database View in Django REST Framework?

Xavier Ordoquy

unread,
Apr 18, 2014, 3:24:24 AM4/18/14
to django-res...@googlegroups.com
Hi Shoaib,

It would help a bit to have the stack trace too in order to understand where the issue comes from.

Regards,
Xavier Ordoquy,
Linovia.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Shoaib Ijaz

unread,
Apr 18, 2014, 3:41:19 AM4/18/14
to django-res...@googlegroups.com
Really Sorry, typo error in my code. I am going to delete this post


Reply all
Reply to author
Forward
0 new messages