zoukankan      html  css  js  c++  java
  • django content-type使用

     1 from django.db import models
     2 
     3 from django.contrib.contenttypes.models import ContentType
     4 from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
     5 # Create your models here.
     6 class Food(models.Model):
     7     name = models.CharField(max_length=32)
     8     coupon = GenericRelation("Coupon")
     9 class Cloth(models.Model):
    10     name = models.CharField(max_length=32)
    11     coupon = GenericRelation("Coupon")
    12 class Coupon(models.Model):
    13 
    14     name = models.CharField("活动名称",max_length=64)
    15     brief = models.TextField(blank=True,null=True,verbose_name="优惠券介绍")
    16     content_type = models.ForeignKey(ContentType,blank=True,null=True) # 代表哪个app下的哪张表
    17     object_id = models.PositiveIntegerField("绑定商品",blank=True,null=True) # 代表哪张表中的对象id
    18     content_obj = GenericForeignKey("content_type","object_id") #不会生成额外的列
    models
     1 from django.shortcuts import render,HttpResponse
     2 from . import models
     3 
     4 def xxx(request):
     5 
     6     # c = models.Cloth.objects.get(id=1)
     7     # models.Coupon.objects.create(name='优惠券',brief='100减10',content_obj=c)
     8 
     9     # c = models.Cloth.objects.get(id=1)
    10     # models.Coupon.objects.create(name='优惠券',brief='200减30',content_obj=c)
    11 
    12     # 查看优惠券绑定的所有商品
    13     # c = models.Coupon.objects.get(id=1)
    14     # print(c.content_obj)
    15 
    16     # 查看该商品下的所有优惠券
    17     c = models.Food.objects.get(id=4)
    18     print(c.coupon.all())
    19     c2 = models.Food.objects.values('name','coupon__brief')
    20     print(c2)
    21     c3 = models.Coupon.objects.get(id=1)
    22     print(c3.content_obj)
    23 
    24     return HttpResponse('ok')
    views

    摘自:https://www.cnblogs.com/c491873412/p/7892585.html

  • 相关阅读:
    洛谷 P1464 Function(简单记忆化)
    LightOJ 1422 Halloween Costumes (区间DP)
    POJ 3280 Cheapest Palindrome(区间DP)
    POJ 2955 Brackets(区间DP)
    洛谷 P1880 [NOI1995]石子合并(区间DP)
    POJ 3641 Pseudoprime numbers(快速幂)
    POJ 2142 The Balance(exgcd)
    POJ 1995 Raising Modulo Numbers(快速幂)
    POJ 2115 C Looooops(exgcd)
    ZOJ 1002 Fire Net(dfs)
  • 原文地址:https://www.cnblogs.com/fenglin0826/p/8476091.html
Copyright © 2011-2022 走看看