django 复合类型

表结构

  • 商品表
  • 店铺表
  • 收藏关系表
  • 人员表

人收藏商品,人收藏店铺, 收藏的关系保存在 收藏关系表中

models.py

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

# Create your models here.
from accounts.models import Student


class Product(models.Model):
    """商品表"""
    name = models.CharField('商品名称',max_length=64)
    collections = GenericRelation(to="Collection")  # 反向查询

    class Meta:
        db_table = 'product'
        verbose_name = verbose_name_plural = '商品表'


class Store(models.Model):
    """店铺表"""
    name = models.CharField('店铺名称',max_length=64)
    collections = GenericRelation(to="Collection")  # 反向查询

    class Meta:
        db_table = 'store'
        verbose_name = verbose_name_plural = '店铺表'


class Collection(models.Model):
    """收藏表"""
    user = models.ForeignKey(Student,on_delete=models.CASCADE)
    content_type = models.ForeignKey(
        to=ContentType,
        limit_choices_to={
            "model__in": (
                "product",
                "store",
            )
        },
        related_name="collection",
        help_text="不同收藏类型",
        on_delete=models.CASCADE
    )
    object_id = models.IntegerField("关联ID", help_text="关联ID")
    content_object = GenericForeignKey()
    created_at = models.DateTimeField('创建时间',auto_now_add=True)
    updated_at = models.DateTimeField("更新时间",auto_now=True)

    class Meta:
        verbose_name = verbose_name_plural = "收藏记录"
        db_table = 'collection'

view.py 调用测试

def get_user_connect(request):
    student = Student.objects.all()
    for s in student:
        # print(s.id)
        k = s.collection_set.all()
        print(k,s)

        for p in k.filter(content_type__model="product"):
            print(p.content_object.name)
        for s in k.filter(content_type__model="store"):
            print(s.content_object.name)

    return HttpResponse("OK")

原文链接: django 复合类型 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-750.html )

发表评论

0则评论给“django 复合类型”