django 根据外键查询另一个表的数据_Django学习之django自带的contentType表

通过django的contentType表来搞定一个表里面有多个外键的简单处理。

    contenttypes 是Django内置的一个应用,可以追踪项目中所有app和model的对应关系,并记录在ContentType表中。

    models.py文件的表结构写好后,通过makemigrations和migrate两条命令迁移数据后,在数据库中会自动生成一个django_content_type表,比如我们有在models.py中写了这么几张表:

from django.db import modelsclass 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)
dd537fb2536d737965db13c01c62081f.png

  如果是通用优惠券,那么所有的ForeignKey为null,如果仅限某些商品,那么对应商品ForeignKey记录该商品的id,不相关的记录为null。但是这样做是有问题的:实际中商品品类繁多,而且很可能还会持续增加,那么优惠券表中的外键将越来越多,但是每条记录仅使用其中的一个或某几个外键字段。

  contenttypes 应用

    通过使用contenttypes 应用中提供的特殊字段GenericForeignKey,我们可以很好的解决这个问题。只需要以下三步:

    在model中定义ForeignKey字段,并关联到ContentType表。通常这个字段命名为“content_type”

    在model中定义PositiveIntegerField字段,用来存储关联表中的主键。通常这个字段命名为“object_id”

    在model中定义GenericForeignKey字段,传入上述两个字段的名字。

    为了更方便查询商品的优惠券,我们还可以在商品类中通过GenericRelation字段定义反向关系。

  示例代码:models.py文件:

from django.db import modelsfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.contenttypes.fields import GenericForeignKey, GenericRelationclass Electrics(models.Model):    name = models.CharField(max_length=32)    price = models.IntegerField(default=100)    coupons = GenericRelation(to='Coupon')  # 用于反向查询,不会生成表字段    def __str__(self):        return self.nameclass Foods(models.Model):    name = models.CharField(max_length=32)    price=models.IntegerField(default=100)    coupons = GenericRelation(to='Coupon')    def __str__(self):        return self.nameclass Clothes(models.Model):    name = models.CharField(max_length=32)    price = models.IntegerField(default=100)    coupons = GenericRelation(to='Coupon')    def __str__(self):        return self.nameclass 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

  注意:ContentType只运用于1对多的关系!!!并且多的那张表中有多个ForeignKey字段。

  数据化迁移,再给每张表添加数据

  衣服表,电器表,床上用品表,美食表

  添加完之后,数据迁移,python manage.py makemigrations 和 python manage.py migrate

创建记录和查询from django.shortcuts import render, HttpResponsefrom api import modelsfrom django.contrib.contenttypes.models import ContentTypedef 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)

  总结: 当一张表和多个表FK关联,并且多个FK中只能选择其中一个或其中n个时,可以利用contenttypes app,只需定义三个字段就搞定!

  创建记录

    关系表的结构

b9033fadbdcb3c4f3a804bbb7e25c168.png

  用语法给关系表加记录。

  添加方式1:

d9cd3cecbc5ab01f95c7eac10ea64106.png
6d9836a9a151d47ca358b7c137641d97.png

  接下来用postmen来发送请求

8a6a3b205c2314eab9c892001c9007f3.png

  然后代金券表数据就添加完成了

3f52e109647bc4ac3e9b9584cf4ef62b.png

  添加方式2:

db8cd733fcc58a9df359db56db831138.png

  通过postmen发送请求结果

c57514b50d209821580f97177815f70f.png

  查询记录

  查询name="电商1代金券"的代金券信息

d72071897bf30fbefd62e462d631f0df.png
5b3995769374a61664b9959e95a6b71f.png

最后,小编想说:我是一名python开发工程师,整理了一套最新的python系统学习教程,想要这些资料的可以关注私信小编“01”即可,希望能对你有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值