Django外键查询及@property在model中的妙用
来源:互联网 发布:渔民之家钓鱼源码 编辑:程序博客网 时间:2024/05/21 08:48
上篇文章中聊了聊@property的用法,这篇文章则聊聊@property在数据库model中的一些小技巧,同时也会涉及些Django在数据库建模的过程中,外键查询和反向查询方面的内容。
不多说,看例子
from django.db import models class Person(models.Model): name = models.CharField(max_length=64) age = models.IntegerField() tel = models.CharField(max_length=64) @property def all_cars(self): return cars.all() @property def info(self): # return the name and tel of person return '%s %s' % (self.name, self.tel) class Car(models.Model): owner = models.Foreignkey(Person, related_name='cars') name = models.CharField(max_length=64) price = models.FloatField()
在上面的两个表中,Person表是主表,Car是字表,Car表外键至Person表。
子表查询主表:
car = Car.objects.get(id=1) # 查询该车的车主 owner = car.owner
主表查询子表,即反向查询:
Tom = Person.objects.get(id=1) # 查询此人有多少车 # 方式一: # Django默认每个主表对象都有一个外键的属性 # 可以通过它来查询所有属于主表的子表信息 # 查询方式:主表.子表_set() # 返回值为一个queryset对象 Tom.Car_set().all() # 方式二: # 通过在外键中设置related_name属性值既可 Tom.cars.all() # 方式三: # 通过@property装饰器在model中预定义方法实现 Tom.all_cars
查询一些自己需要的组合数据,比如获取某人的关键信息
Tom.info
另外,在新的需求突然提出的时候,在不改动原有查询代码的情况下,在表模型中添加此装饰器装饰过的方法既可。
2 0
- Django外键查询及@property在model中的妙用
- KVC在定义Model类中的妙用
- KVC在定义Model类中的妙用
- KVC在定义Model类中的妙用
- Django Model 查询
- django关于model查询
- Django中的Model继承
- django model filter 条件过滤,及多表连接查询、反向查询,某字段的distinct
- django model filter 条件过滤,及多表连接查询、反向查询,某字段的distinct
- 鼠标中键在Firefox中的妙用
- redisco,django中的Model共存
- Django model中的元选项
- ROST在SupremeWord及Supermemo软件中的妙用
- django ORM model filter 条件过滤,及多表连接查询、反向查询 和 多条件查询
- How to replace a Django model field with a property
- Django-model一对多关系查询
- django ORM model filter 条件过滤,及多表连接查询、反向查询,某字段的distinct
- django ORM model filter 条件过滤,及多表连接查询、反向查询,某字段的distinct
- iOS --调用webservice接口
- 扬帆起航,再踏征程(三)
- 网易邵峰:移动直播视频流分发网络的演进
- [编程题]数据分类处理
- ViewPager简单示例
- Django外键查询及@property在model中的妙用
- SHA1WithRSA签名使用openssl 实现
- GC算法 垃圾收集器
- 大数据时代的地理信息系统发展
- 【Set】 迭代
- 这是一个冒泡排序
- calloc,ralloc如何使用,使用的注意事项
- MySQL casting from decimal to string(mysql decimal 转 varchar)
- 内核模块