django 17.Django learning comes contentType table

    The contentType table by django get a table which has a simple processing a plurality of outer keys: Adapted from: https://blog.csdn.net/aaronthon/article/details/81714496

    contenttypes Django is a built-in application, all correspondence between the model and the app can track projects, and recorded in the ContentType table.

    After the file is written models.py table structure, command and migrate to migrate data by makemigrations two, django_content_type automatically generates a table in the database, such as we have written so few tables in models.py in:

from django.db import models

class Electrics(models.Model):
    """
    id    name
     1   日立冰箱
     2   三星电视
     3   小天鹅洗衣机
    """
    name = models.CharField(max_length=32)


class Foods(models.Model):
    """
    id   name
    1    面包
    2    烤鸭
    """
    name = models.CharField(max_length=32)


class Clothes(models.Model):
    name = models.CharField(max_length=32)


class Coupon(models.Model):  # 特殊关系表
""" 
  id    name    electric_id   food_id   cloth_id   more...   # 每增加一张表,关系表的结构就要多加一个字段。
    1   通用优惠券   null       null      null 
    2   冰箱满减券   2         null     null 
    3   面包狂欢节   null        1      null 
""" 
name = models.CharField(max_length=32) 
electric = models.ForeignKey(to='Electrics', null=True) 
food = models.ForeignKey(to='Foods', null=True) 
cloth = models.ForeignKey(to='Clothes', null=True)

    

      img

    

    

  If the coupon is universal, then all ForeignKey is null, if only some of the goods, then the corresponding commodity ForeignKey record id of the goods, not related record is null. But doing so is problematic: in practice many kinds of goods, and probably will continue to increase, then the foreign key table coupons will be more and more, but each record using only one or a few of them outside key field.

  contenttypes application

    By using a special field GenericForeignKey contenttypes applications provided, we can solve this problem. Only the following three steps:

    ForeignKey fields defined in the model, and associated with ContentType table. Normally this field named "content_type"

    PositiveIntegerField model defined in the field, to store the associated primary key in the table. Normally this field named "object_id"

    GenericForeignKey defined in the model in the field, passing the name of these two fields.

    In order to facilitate inquiries merchandise coupons, we can also define the inverse relationship GenericRelation field by commodity class.

  Sample code: models.py file:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation


class Electrics(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField(default=100)
    coupons = GenericRelation(to='Coupon')  # 用于反向查询,不会生成表字段

    def __str__(self):
        return self.name


class Foods(models.Model):
    name = models.CharField(max_length=32)
    price=models.IntegerField(default=100)
    coupons = GenericRelation(to='Coupon')

    def __str__(self):
        return self.name


class Clothes(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField(default=100)
    coupons = GenericRelation(to='Coupon')

    def __str__(self):
        return self.name


class bed(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField(default=100)
    coupons = GenericRelation(to='Coupon')


class Coupon(models.Model):
    """
    Coupon
        id    name                      content_type_id       object_id_id
              美的满减优惠券                    9(电器表electrics)   3
              猪蹄买一送一优惠券                10                    2
              南极被子买200减50优惠券           11                    1
    """
    name = models.CharField(max_length=32)

    content_type = models.ForeignKey(to=ContentType,on_delete=models.CASCADE) # step 1 既然没有直接和关联表进行外键关系,我们通过这一步先找到关联表
    object_id = models.PositiveIntegerField() # step 2  #存的是关联的那个表的对应的那条记录的id
    content_object = GenericForeignKey('content_type', 'object_id') # step 3  对象.content_object直接就拿到了这个优惠券对象关联的那个商品记录对象。

    def __str__(self):
        return self.name

  Note: ContentType only applied to one relationship and more! ! ! And there are many that table ForeignKey plurality of fields.

  Data migration, give each table to add data

  Table clothes, electrical tables, bedding, table, food table

  After you have added, data migration, python manage.py makemigrations and python manage.py migrate

创建记录和查询

from django.shortcuts import render, HttpResponse
from api import models
from django.contrib.contenttypes.models import ContentType


def test(request):
    if request.method == 'GET':
        # ContentType表对象有model_class() 方法,取到对应model
        content = ContentType.objects.filter(app_label='api', model='electrics').first()  # 表名小写
        cloth_class = content.model_class() # cloth_class 就相当于models.Electrics
        res = cloth_class.objects.all()
        print(res)

        # 为三星电视(id=2)创建一条优惠记录
        s_tv = models.Electrics.objects.filter(id=2).first()
        models.Coupon.objects.create(name='电视优惠券', content_object=s_tv)

        # 查询优惠券(id=1)绑定了哪个商品
        coupon_obj = models.Coupon.objects.filter(id=1).first()
        prod = coupon_obj.content_object
        print(prod)

        # 查询三星电视(id=2)的所有优惠券
        res = s_tv.coupons.all()
        print(res)

  

  Summary: When a plurality of tables and a table associated FK, and wherein the plurality of FK can only select a time or where the n, may be utilized contenttypes app, simply define three fields to get!

  Create a record

    The structure of relational tables

    img

  The syntax to use relational tables plus record.

  Add Mode 1:

    img

    img

    

  Next request is sent by postmen

    img

  Then vouchers table data is added to complete the

    img

  Add 2 ways:

    img

  Sending a request results postmen

    img

  inquiry record

  Query name = "1 electricity supplier vouchers" Vouchers Information

    img

    img

Guess you like

Origin www.cnblogs.com/changxin7/p/12033148.html