django的orm--contenttype操作
阿新 • • 發佈:2018-03-02
http closed 反向 自動生成 pan BE ger 包含 其他
1,在django操作orm生成表時,會自動生成一個包含所有表名稱的表.
名字就叫:
2,實際操作.
class PricePolicy(models.Model): """價格與有課程效期表""" content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey(‘content_type‘, ‘object_id‘) valid_period_choicesmodel= ((1, ‘1天‘), (3, ‘3天‘), (7, ‘1周‘), (14, ‘2周‘), (30, ‘1個月‘), (60, ‘2個月‘), (90, ‘3個月‘), (180, ‘6個月‘), (210, ‘12個月‘), (540, ‘18個月‘), (720, ‘24個月‘), ) valid_period = models.SmallIntegerField(choices=valid_period_choices) price = models.FloatField() class Course(models.Model): attachment_path = models.CharField(max_length=128, verbose_name="課件路徑", blank=True, null=True) status_choices = ((0, ‘上線‘), (1, ‘下線‘), (2, ‘預上線‘)) status = models.SmallIntegerField(choices=status_choices, default=0) template_id = models.SmallIntegerField("前端模板id", default=1) coupon = GenericRelation("Coupon") # 用於GenericForeignKey反向查詢,不會生成表字段,切勿刪除 price_policy = GenericRelation("PricePolicy")
course_obj=models.Course.object.filter(id=1) price_list=course_obj.price_policy.all() #獲取與之關聯的price_policy的所有對象 for price in price_list: #獲取所有字段,和操作其他orm一樣. print(price.valid_period) print(price.price)view
上面是反向查詢,下面是正向查詢
price_obj=models.PricePolicy.objects.filter(id=1) status=price_obj.content_type.status #可以直接通過content_type查詢course表中字段
django的orm--contenttype操作