| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
 | <!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Generic views - Django REST framework</title>
  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
  <link rel="canonical" href="http://www.django-rest-framework.org/api-guide/generic-views/" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Django, API, REST, Generic views">
  <meta name="author" content="Tom Christie">
  <!-- Le styles -->
  <link href="../../css/prettify.css" rel="stylesheet">
  <link href="../../css/bootstrap.css" rel="stylesheet">
  <link href="../../css/bootstrap-responsive.css" rel="stylesheet">
  <link href="../../css/default.css" rel="stylesheet">
  <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
  <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-18852272-2']);
    _gaq.push(['_trackPageview']);
    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();
  </script>
  <style>
    span.fusion-wrap a {
      display: block;
      margin-top: 10px;
      color: black;
    }
    a.fusion-poweredby {
      display: block;
      margin-top: 10px;
    }
    @media (max-width: 767px) {
      div.promo {
        display: none;
      }
    }
  </style>
</head>
<body onload="prettyPrint()" class="-page">
  <div class="wrapper">
        <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
          <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
          <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../viewsets">
            Next <i class="icon-arrow-right icon-white"></i>
          </a>
          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../views">
            <i class="icon-arrow-left icon-white"></i> Previous
          </a>
          <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
          <div class="nav-collapse collapse">
            
            <!-- Main navigation -->
            <ul class="nav navbar-nav">
              <li ><a href="/">Home</a></li>
               
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../tutorial/quickstart">Quickstart</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/1-serialization">1 - Serialization</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/2-requests-and-responses">2 - Requests and responses</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/3-class-based-views">3 - Class based views</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/6-viewsets-and-routers">6 - Viewsets and routers</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown active">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../requests">Requests</a>
                  </li>
                  
                  <li >
                    <a href="../responses">Responses</a>
                  </li>
                  
                  <li >
                    <a href="../views">Views</a>
                  </li>
                  
                  <li class="active" >
                    <a href=".">Generic views</a>
                  </li>
                  
                  <li >
                    <a href="../viewsets">Viewsets</a>
                  </li>
                  
                  <li >
                    <a href="../routers">Routers</a>
                  </li>
                  
                  <li >
                    <a href="../parsers">Parsers</a>
                  </li>
                  
                  <li >
                    <a href="../renderers">Renderers</a>
                  </li>
                  
                  <li >
                    <a href="../serializers">Serializers</a>
                  </li>
                  
                  <li >
                    <a href="../fields">Serializer fields</a>
                  </li>
                  
                  <li >
                    <a href="../relations">Serializer relations</a>
                  </li>
                  
                  <li >
                    <a href="../validators">Validators</a>
                  </li>
                  
                  <li >
                    <a href="../authentication">Authentication</a>
                  </li>
                  
                  <li >
                    <a href="../permissions">Permissions</a>
                  </li>
                  
                  <li >
                    <a href="../throttling">Throttling</a>
                  </li>
                  
                  <li >
                    <a href="../filtering">Filtering</a>
                  </li>
                  
                  <li >
                    <a href="../pagination">Pagination</a>
                  </li>
                  
                  <li >
                    <a href="../versioning">Versioning</a>
                  </li>
                  
                  <li >
                    <a href="../content-negotiation">Content negotiation</a>
                  </li>
                  
                  <li >
                    <a href="../metadata">Metadata</a>
                  </li>
                  
                  <li >
                    <a href="../format-suffixes">Format suffixes</a>
                  </li>
                  
                  <li >
                    <a href="../reverse">Returning URLs</a>
                  </li>
                  
                  <li >
                    <a href="../exceptions">Exceptions</a>
                  </li>
                  
                  <li >
                    <a href="../status-codes">Status codes</a>
                  </li>
                  
                  <li >
                    <a href="../testing">Testing</a>
                  </li>
                  
                  <li >
                    <a href="../settings">Settings</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../topics/documenting-your-api">Documenting your API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/internationalization">Internationalization</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browser-enhancements">Browser enhancements</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browsable-api">The Browsable API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/third-party-resources">Third Party Resources</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/contributing">Contributing to REST framework</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/project-management">Project management</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/3.0-announcement">3.0 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/3.1-announcement">3.1 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/release-notes">Release Notes</a>
                  </li>
                  
                </ul>
              </li>
               
            </ul>
            
          </div>
          <!--/.nav-collapse -->
        </div>
      </div>
    </div>
    <div class="body-content">
      <div class="container-fluid">
        <!-- Search Modal -->
        <div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">Documentation search</h3>
          </div>
          <div class="modal-body">
            <!-- Custom google search -->
            <script>
              (function() {
                var cx = '015016005043623903336:rxraeohqk6w';
                var gcse = document.createElement('script');
                gcse.type = 'text/javascript';
                gcse.async = true;
                gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
                  '//www.google.com/cse/cse.js?cx=' + cx;
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(gcse, s);
              })();
            </script>
            <gcse:search></gcse:search>
          </div>
          <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          </div>
        </div>
        <div class="row-fluid">
          <div class="span3">
            <!-- TODO
            <p style="margin-top: -12px">
              <a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
              <a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
            </p>
          -->
            <div id="table-of-contents">
              <ul class="nav nav-list side-nav well sidebar-nav-fixed">
                
                
                  <li class="main">
                    <a href="#generic-views">Generic views</a>
                  </li>
                  
                    <li>
                      <a href="#examples">Examples</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#api-reference">API Reference</a>
                  </li>
                  
                    <li>
                      <a href="#genericapiview">GenericAPIView</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#mixins">Mixins</a>
                  </li>
                  
                    <li>
                      <a href="#listmodelmixin">ListModelMixin</a>
                    </li>
                  
                    <li>
                      <a href="#createmodelmixin">CreateModelMixin</a>
                    </li>
                  
                    <li>
                      <a href="#retrievemodelmixin">RetrieveModelMixin</a>
                    </li>
                  
                    <li>
                      <a href="#updatemodelmixin">UpdateModelMixin</a>
                    </li>
                  
                    <li>
                      <a href="#destroymodelmixin">DestroyModelMixin</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#concrete-view-classes">Concrete View Classes</a>
                  </li>
                  
                    <li>
                      <a href="#createapiview">CreateAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#listapiview">ListAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#retrieveapiview">RetrieveAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#destroyapiview">DestroyAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#updateapiview">UpdateAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#listcreateapiview">ListCreateAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#retrieveupdateapiview">RetrieveUpdateAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#retrievedestroyapiview">RetrieveDestroyAPIView</a>
                    </li>
                  
                    <li>
                      <a href="#retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#customizing-the-generic-views">Customizing the generic views</a>
                  </li>
                  
                    <li>
                      <a href="#creating-custom-mixins">Creating custom mixins</a>
                    </li>
                  
                    <li>
                      <a href="#creating-custom-base-classes">Creating custom base classes</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#put-as-create">PUT as create</a>
                  </li>
                  
                
                  <li class="main">
                    <a href="#third-party-packages">Third party packages</a>
                  </li>
                  
                    <li>
                      <a href="#django-rest-framework-bulk">Django REST Framework bulk</a>
                    </li>
                  
                
                
              </ul>
            </div>
          </div>
          <div id="main-content" class="span9">
            
              
                <a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/mixins.py">
                  <span class="label label-info">mixins.py</span>
                </a>
              
                <a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/generics.py">
                  <span class="label label-info">generics.py</span>
                </a>
              
            
            <h1 id="generic-views">Generic views</h1>
<blockquote>
<p>Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.</p>
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views">Django Documentation</a></p>
</blockquote>
<p>One of the key benefits of class based views is the way they allow you to compose bits of reusable behavior.  REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.</p>
<p>The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.</p>
<p>If the generic views don't suit the needs of your API, you can drop down to using the regular <code>APIView</code> class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.</p>
<h2 id="examples">Examples</h2>
<p>Typically when using the generic views, you'll override the view, and set several class attributes.</p>
<pre><code>from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics
from rest_framework.permissions import IsAdminUser
class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAdminUser,)
    paginate_by = 100
</code></pre>
<p>For more complex cases you might also want to override various methods on the view class.  For example.</p>
<pre><code>class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAdminUser,)
    def get_paginate_by(self):
        """
        Use smaller pagination for HTML representations.
        """
        if self.request.accepted_renderer.format == 'html':
            return 20
        return 100
    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)
</code></pre>
<p>For very simple cases you might want to pass through any class attributes using the <code>.as_view()</code> method.  For example, your URLconf might include something like the following entry:</p>
<pre><code>url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
</code></pre>
<hr />
<h1 id="api-reference">API Reference</h1>
<h2 id="genericapiview">GenericAPIView</h2>
<p>This class extends REST framework's <code>APIView</code> class, adding commonly required behavior for standard list and detail views.</p>
<p>Each of the concrete generic views provided is built by combining <code>GenericAPIView</code>, with one or more mixin classes.</p>
<h3 id="attributes">Attributes</h3>
<p><strong>Basic settings</strong>:</p>
<p>The following attributes control the basic view behavior.</p>
<ul>
<li><code>queryset</code> - The queryset that should be used for returning objects from this view.  Typically, you must either set this attribute, or override the <code>get_queryset()</code> method. If you are overriding a view method, it is important that you call <code>get_queryset()</code> instead of accessing this property directly, as <code>queryset</code> will get evaluated once, and those results will be cached for all subsequent requests.</li>
<li><code>serializer_class</code> - The serializer class that should be used for validating and deserializing input, and for serializing output.  Typically, you must either set this attribute, or override the <code>get_serializer_class()</code> method.</li>
<li><code>lookup_field</code> - The model field that should be used to for performing object lookup of individual model instances.  Defaults to <code>'pk'</code>.  Note that when using hyperlinked APIs you'll need to ensure that <em>both</em> the API views <em>and</em> the serializer classes set the lookup fields if you need to use a custom value.</li>
<li><code>lookup_url_kwarg</code> - The URL keyword argument that should be used for object lookup.  The URL conf should include a keyword argument corresponding to this value.  If unset this defaults to using the same value as <code>lookup_field</code>.</li>
</ul>
<p><strong>Pagination</strong>:</p>
<p>The following attributes are used to control pagination when used with list views.</p>
<ul>
<li><code>pagination_class</code> - The pagination class that should be used when paginating list results. Defaults to the same value as the <code>DEFAULT_PAGINATION_CLASS</code> setting, which is <code>'rest_framework.pagination.PageNumberPagination'</code>.</li>
</ul>
<p>Note that usage of the <code>paginate_by</code>, <code>paginate_by_param</code> and <code>page_kwarg</code> attributes are now pending deprecation. The <code>pagination_serializer_class</code> attribute and <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> setting have been removed completely. Pagination settings should instead be controlled by overriding a pagination class and setting any configuration attributes there. See the pagination documentation for more details.</p>
<p><strong>Filtering</strong>:</p>
<ul>
<li><code>filter_backends</code> - A list of filter backend classes that should be used for filtering the queryset.  Defaults to the same value as the <code>DEFAULT_FILTER_BACKENDS</code> setting.</li>
</ul>
<h3 id="methods">Methods</h3>
<p><strong>Base methods</strong>:</p>
<h4 id="get_querysetself"><code>get_queryset(self)</code></h4>
<p>Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views.  Defaults to returning the queryset specified by the <code>queryset</code> attribute.</p>
<p>This method should always be used rather than accessing <code>self.queryset</code> directly, as <code>self.queryset</code> gets evaluated only once, and those results are cached for all subsequent requests.</p>
<p>May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.</p>
<p>For example:</p>
<pre><code>def get_queryset(self):
    user = self.request.user
    return user.accounts.all()
</code></pre>
<h4 id="get_objectself"><code>get_object(self)</code></h4>
<p>Returns an object instance that should be used for detail views.  Defaults to using the <code>lookup_field</code> parameter to filter the base queryset.</p>
<p>May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.</p>
<p>For example:</p>
<pre><code>def get_object(self):
    queryset = self.get_queryset()
    filter = {}
    for field in self.multiple_lookup_fields:
        filter[field] = self.kwargs[field]
    obj = get_object_or_404(queryset, **filter)
    self.check_object_permissions(self.request, obj)
    return obj
</code></pre>
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>self.check_object_permissions</code>, and simply return the object from the <code>get_object_or_404</code> lookup.</p>
<h4 id="get_filter_backendsself"><code>get_filter_backends(self)</code></h4>
<p>Returns the classes that should be used to filter the queryset. Defaults to returning the <code>filter_backends</code> attribute.</p>
<p>May be overridden to provide more complex behavior with filters, such as using different (or even exlusive) lists of filter_backends depending on different criteria.</p>
<p>For example:</p>
<pre><code>def get_filter_backends(self):
    if "geo_route" in self.request.QUERY_PARAMS:
        return (GeoRouteFilter, CategoryFilter)
    elif "geo_point" in self.request.QUERY_PARAMS:
        return (GeoPointFilter, CategoryFilter)
    return (CategoryFilter,)
</code></pre>
<h4 id="get_serializer_classself"><code>get_serializer_class(self)</code></h4>
<p>Returns the class that should be used for the serializer.  Defaults to returning the <code>serializer_class</code> attribute.</p>
<p>May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.</p>
<p>For example:</p>
<pre><code>def get_serializer_class(self):
    if self.request.user.is_staff:
        return FullAccountSerializer
    return BasicAccountSerializer
</code></pre>
<h4 id="get_paginate_byself"><code>get_paginate_by(self)</code></h4>
<p>Returns the page size to use with pagination.  By default this uses the <code>paginate_by</code> attribute, and may be overridden by the client if the <code>paginate_by_param</code> attribute is set.</p>
<p>You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.</p>
<p>For example:</p>
<pre><code>def get_paginate_by(self):
    if self.request.accepted_renderer.format == 'html':
        return 20
    return 100
</code></pre>
<p><strong>Save and deletion hooks</strong>:</p>
<p>The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.</p>
<ul>
<li><code>perform_create(self, serializer)</code> - Called by <code>CreateModelMixin</code> when saving a new object instance.</li>
<li><code>perform_update(self, serializer)</code> - Called by <code>UpdateModelMixin</code> when saving an existing object instance.</li>
<li><code>perform_destroy(self, instance)</code> - Called by <code>DestroyModelMixin</code> when deleting an object instance.</li>
</ul>
<p>These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data.  For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.</p>
<pre><code>def perform_create(self, serializer):
    serializer.save(user=self.request.user)
</code></pre>
<p>These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.</p>
<pre><code>def perform_update(self, serializer):
    instance = serializer.save()
    send_email_confirmation(user=self.request.user, modified=instance)
</code></pre>
<p><strong>Note</strong>: These methods replace the old-style version 2.x <code>pre_save</code>, <code>post_save</code>, <code>pre_delete</code> and <code>post_delete</code> methods, which are no longer available.</p>
<p><strong>Other methods</strong>:</p>
<p>You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using <code>GenericAPIView</code>.</p>
<ul>
<li><code>get_serializer_context(self)</code> - Returns a dictionary containing any extra context that should be supplied to the serializer.  Defaults to including <code>'request'</code>, <code>'view'</code> and <code>'format'</code> keys.</li>
<li><code>get_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=False)</code> - Returns a serializer instance.</li>
<li><code>get_pagination_serializer(self, page)</code> - Returns a serializer instance to use with paginated data.</li>
<li><code>paginate_queryset(self, queryset)</code> - Paginate a queryset if required, either returning a page object, or <code>None</code> if pagination is not configured for this view.</li>
<li><code>filter_queryset(self, queryset)</code> - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.</li>
</ul>
<hr />
<h1 id="mixins">Mixins</h1>
<p>The mixin classes provide the actions that are used to provide the basic view behavior.  Note that the mixin classes provide action methods rather than defining the handler methods, such as <code>.get()</code> and <code>.post()</code>, directly.  This allows for more flexible composition of behavior.</p>
<p>The mixin classes can be imported from <code>rest_framework.mixins</code>.</p>
<h2 id="listmodelmixin">ListModelMixin</h2>
<p>Provides a <code>.list(request, *args, **kwargs)</code> method, that implements listing a queryset.</p>
<p>If the queryset is populated, this returns a <code>200 OK</code> response, with a serialized representation of the queryset as the body of the response.  The response data may optionally be paginated.</p>
<h2 id="createmodelmixin">CreateModelMixin</h2>
<p>Provides a <code>.create(request, *args, **kwargs)</code> method, that implements creating and saving a new model instance.</p>
<p>If an object is created this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.  If the representation contains a key named <code>url</code>, then the <code>Location</code> header of the response will be populated with that value.</p>
<p>If the request data provided for creating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<h2 id="retrievemodelmixin">RetrieveModelMixin</h2>
<p>Provides a <code>.retrieve(request, *args, **kwargs)</code> method, that implements returning an existing model instance in a response.</p>
<p>If an object can be retrieved this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.  Otherwise it will return a <code>404 Not Found</code>.</p>
<h2 id="updatemodelmixin">UpdateModelMixin</h2>
<p>Provides a <code>.update(request, *args, **kwargs)</code> method, that implements updating and saving an existing model instance.</p>
<p>Also provides a <code>.partial_update(request, *args, **kwargs)</code> method, which is similar to the <code>update</code> method, except that all fields for the update will be optional.  This allows support for HTTP <code>PATCH</code> requests.</p>
<p>If an object is updated this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If an object is created, for example when making a <code>DELETE</code> request followed by a <code>PUT</code> request to the same URL, this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If the request data provided for updating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<h2 id="destroymodelmixin">DestroyModelMixin</h2>
<p>Provides a <code>.destroy(request, *args, **kwargs)</code> method, that implements deletion of an existing model instance.</p>
<p>If an object is deleted this returns a <code>204 No Content</code> response, otherwise it will return a <code>404 Not Found</code>.</p>
<hr />
<h1 id="concrete-view-classes">Concrete View Classes</h1>
<p>The following classes are the concrete generic views.  If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.</p>
<p>The view classes can be imported from <code>rest_framework.generics</code>.</p>
<h2 id="createapiview">CreateAPIView</h2>
<p>Used for <strong>create-only</strong> endpoints.</p>
<p>Provides a <code>post</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
<h2 id="listapiview">ListAPIView</h2>
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
<p>Provides a <code>get</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a></p>
<h2 id="retrieveapiview">RetrieveAPIView</h2>
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides a <code>get</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a></p>
<h2 id="destroyapiview">DestroyAPIView</h2>
<p>Used for <strong>delete-only</strong> endpoints for a <strong>single model instance</strong>.</p>
<p>Provides a <code>delete</code> method handler.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<h2 id="updateapiview">UpdateAPIView</h2>
<p>Used for <strong>update-only</strong> endpoints for a <strong>single model instance</strong>.</p>
<p>Provides <code>put</code> and <code>patch</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
<h2 id="listcreateapiview">ListCreateAPIView</h2>
<p>Used for <strong>read-write</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
<p>Provides <code>get</code> and <code>post</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
<h2 id="retrieveupdateapiview">RetrieveUpdateAPIView</h2>
<p>Used for <strong>read or update</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code>, <code>put</code> and <code>patch</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
<h2 id="retrievedestroyapiview">RetrieveDestroyAPIView</h2>
<p>Used for <strong>read or delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code> and <code>delete</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<h2 id="retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</h2>
<p>Used for <strong>read-write-delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
<p>Provides <code>get</code>, <code>put</code>, <code>patch</code> and <code>delete</code> method handlers.</p>
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
<hr />
<h1 id="customizing-the-generic-views">Customizing the generic views</h1>
<p>Often you'll want to use the existing generic views, but use some slightly customized behavior.  If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.</p>
<h2 id="creating-custom-mixins">Creating custom mixins</h2>
<p>For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:</p>
<pre><code>class MultipleFieldLookupMixin(object):
    """
    Apply this mixin to any view or viewset to get multiple field filtering
    based on a `lookup_fields` attribute, instead of the default single field filtering.
    """
    def get_object(self):
        queryset = self.get_queryset()             # Get the base queryset
        queryset = self.filter_queryset(queryset)  # Apply any filter backends
        filter = {}
        for field in self.lookup_fields:
            filter[field] = self.kwargs[field]
        return get_object_or_404(queryset, **filter)  # Lookup the object
</code></pre>
<p>You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.</p>
<pre><code>class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_fields = ('account', 'username')
</code></pre>
<p>Using custom mixins is a good option if you have custom behavior that needs to be used.</p>
<h2 id="creating-custom-base-classes">Creating custom base classes</h2>
<p>If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project.  For example:</p>
<pre><code>class BaseRetrieveView(MultipleFieldLookupMixin,
                       generics.RetrieveAPIView):
    pass
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
                                    generics.RetrieveUpdateDestroyAPIView):
    pass
</code></pre>
<p>Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.</p>
<hr />
<h1 id="put-as-create">PUT as create</h1>
<p>Prior to version 3.0 the REST framework mixins treated <code>PUT</code> as either an update or a create operation, depending on if the object already existed or not.</p>
<p>Allowing <code>PUT</code> as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning <code>404</code> responses.</p>
<p>Both styles "<code>PUT</code> as 404" and "<code>PUT</code> as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.</p>
<p>If you need to generic PUT-as-create behavior you may want to include something like <a href="https://gist.github.com/tomchristie/a2ace4577eff2c603b1b">this <code>AllowPUTAsCreateMixin</code> class</a> as a mixin to your views.</p>
<hr />
<h1 id="third-party-packages">Third party packages</h1>
<p>The following third party packages provide additional generic view implementations.</p>
<h2 id="django-rest-framework-bulk">Django REST Framework bulk</h2>
<p>The <a href="https://github.com/miki725/django-rest-framework-bulk">django-rest-framework-bulk package</a> implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.</p>
          </div>
          <!--/span-->
        </div>
        <!--/row-->
      </div>
      <!--/.fluid-container-->
    </div>
    <!--/.body content-->
    <div id="push"></div>
  </div>
  <!--/.wrapper -->
  <footer class="span12">
    <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a>
    </p>
  </footer>
  <!-- Le javascript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="../../js/jquery-1.8.1-min.js"></script>
  <script src="../../js/prettify-1.0.js"></script>
  <script src="../../js/bootstrap-2.1.1-min.js"></script>
  <script src="../../js/theme.js"></script>
  <script>
    //$('.side-nav').scrollspy()
    var shiftWindow = function() {
      scrollBy(0, -50)
    };
    if (location.hash) shiftWindow();
    window.addEventListener("hashchange", shiftWindow);
    $('.dropdown-menu').on('click touchstart', function(event) {
      event.stopPropagation();
    });
    // Dynamically force sidenav to no higher than browser window
    $('.side-nav').css('max-height', window.innerHeight - 130);
    $(function() {
      $(window).resize(function() {
        $('.side-nav').css('max-height', window.innerHeight - 130);
      });
    });
  </script>
</body>
</html>
 |