1
+ from collections import namedtuple
2
+
1
3
import pytest
2
4
from django .test import TestCase
3
5
from django .urls import reverse
4
6
from django .utils import timezone
5
7
6
- from rest_framework_json_api .serializers import ResourceIdentifierObjectSerializer
8
+ from rest_framework_json_api .serializers import ResourceIdentifierObjectSerializer , ModelSerializer
7
9
from rest_framework_json_api .utils import format_resource_type
8
10
9
11
from example .models import Author , Blog , Entry
@@ -18,8 +20,8 @@ def setUp(self):
18
20
blog = self .blog ,
19
21
headline = 'headline' ,
20
22
body_text = 'body_text' ,
21
- pub_date = timezone .now (),
22
- mod_date = timezone .now (),
23
+ pub_date = timezone .now (). date () ,
24
+ mod_date = timezone .now (). date () ,
23
25
n_comments = 0 ,
24
26
n_pingbacks = 0 ,
25
27
rating = 3
@@ -30,6 +32,36 @@ def setUp(self):
30
32
Author .objects .create (name = name , email = '{}@example.org' .format (name ))
31
33
)
32
34
35
+ def test_forward_relationship_not_loaded_when_not_included (self ):
36
+ MockRequest = namedtuple ('Request' , ['query_params' ])
37
+ request_without_includes = MockRequest ({})
38
+ to_representation_was_called = False
39
+
40
+ class BlogSerializer (ModelSerializer ):
41
+ class Meta :
42
+ model = Blog
43
+ fields = '__all__'
44
+
45
+ def to_representation (self , instance ):
46
+ nonlocal to_representation_was_called
47
+ to_representation_was_called = True
48
+ return super ().to_representation (instance )
49
+
50
+ class EntrySerializer (ModelSerializer ):
51
+ blog = BlogSerializer ()
52
+
53
+ class Meta :
54
+ model = Entry
55
+ fields = '__all__'
56
+
57
+ included_serializers = {
58
+ 'blog' : BlogSerializer ,
59
+ }
60
+
61
+ serializer = EntrySerializer (context = {'request' : request_without_includes })
62
+ serializer .to_representation (self .entry )
63
+ self .assertFalse (to_representation_was_called )
64
+
33
65
def test_data_in_correct_format_when_instantiated_with_blog_object (self ):
34
66
serializer = ResourceIdentifierObjectSerializer (instance = self .blog )
35
67
0 commit comments