Database API ForeignKey

 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
#create ForeignKey
user = User.objects.get(pk=13)
Blog.objects.create(name='Some Name', author=user)
user = User.objects.get(pk=13)
b = Blog(name='Some Name', author=user)
b.save()
###########################################################################
#update ForeignKey
user = User.objects.get(pk=13)
b = Blog.objects.get(pk=5)
b.author = user
b.save()
###########################################################################
# delete
b = Blog.objects.get(pk=5)
b.delete()
# or
user = User.objects.get(pk=5)
blogs = Blog.objects.filter(user=user)
for i in blogs:
i.delete()
user.delete()
##########################################################################
# show
Blog.objects.filter(foreign__id=5)
#or
Blog.objects.filter(foreign=5)
#or
ForeignObject = User.objects.get(pk=5)
Blog.objects.filter(forign=ForeignObject)
#or
Blog.objects.filter(foreign__pk=5)
# show reverse
Foreign.objects.filter(blog__id=5)