class UserType(models.Model):
caption = models.CharField(max_length=32)
class UserInfo(models.Model):
user_type = models.ForeignKey(UserType)# user_type对象中封装id,caption
username = models.CharField(max_length=32)
Select | insert | |||
一对多 | django | 正向 | 1.Models.userinfo.objects.filter(user_type__caption=xxx) 用户类型为xxx的用记 2. models.UserInfo.objects.select_related().all() 两个表做join | 1.models.UserInfo.objects.create(username=’xx’,user_type_id=n) 2.models.UserInfo.objects.create(username=’xx’, user_type=models.UserType.objects.get(caption=’xx’),age=m) |
反向 | 1. obj= models.UserType.objects.all() 2.obj=models.UserType.objects.filter(userinfo__age__gt=33) usertype创建后会对应的创建一个与子表名(userinfo)对应的列 userinfo指向子表 3. obj=models.UserType.objects.get(caption=‘ceo‘).userinfo_set.all()
| ---- | ||
前端 | 正向 | 1. obj.user_name obj.user_type.caption 2. 与1 一样 | ----- | |
反向 | 1.obj.caption obj.userinfo_set.first.username 2. 与 1 一样 3.obj.username or obj.age | ------ | ||
class Host(models.Model): hostname = models.CharField(max_length=32) class HostAdmin(models.Model): username = models.CharField(max_length=32) host = models.ManyToManyField(Host)
| ||||
多对多 | django | 正向 | 1.models.HostAdmin.objects.filter(host__hostname=‘host1‘).values() 管理host1的所有用户 2.admin_obj=models.HostAdmin.objects.filter(host__hostname__in=(‘host1‘,‘host2‘)).values().distinct() 管理host1 或 host2的所有用户
| 1.admin_obj = models.HostAdmin.objects.get(username=‘user1‘)
|
反向 | 1. obj = models.Host.objects.get(id=3).hostadmin_set.all() Id=3的主机对应的管理员 2.obj = models.Host.objects.filter(hostadmin__username=‘user1‘) 管理员为user1 对应的主机 | 1. host_obj = models.Host.objects.get(id=3) admin_obj_list =models.HostAdmin.objects.filter(id__gt=1) host_obj.hostadmin_set.add(*admin_obj_list)
| ||
前端 | 正向 | 1.admin.username 2. {% for admin in admin_obj %} 此处的all可以改为values,但如果改成values_list,后面就需要改成host.1 (1为index值)
| ------- | |
反向 | 1.obj.username 2.obj.hostname | ------------- |
注:1.表名_set只能跟在结果后面,不能跟在结果集后面
原文地址:http://120662.blog.51cto.com/110662/1766949