m2m数据操作

model定义

class Article(models.Model):
    userid = models.ForeignKey(User, null=True, blank=True, verbose_name='登陆人',on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='article/%Y%m%d/', null=True,blank=True)
    category = models.ManyToManyField(Category, null=True,blank=True,verbose_name="分类" )

 

 

article数据

 catagory数据

 

 

def m2morm():
    # uid = [{'id':obj.id,'name':obj.name,'urlid':obj.urlid,'parent_id':obj.parent_code } for obj in Category.objects.filter(level='1')]
    c1 = Category.objects.get(id=15)
    c2 = Category.objects.get(id=20)
    c3 = Category.objects.get(id=32)
    a1 = Article.objects.get(id=126)
    a2 = Article.objects.get(id=127)
    a3 = Article.objects.get(id=128)
    # 一。1、article 添加catagroy:  重复添加没问题
    # a1.category.add(c2)
    # a2.category.add(c1,c2,c3)

    list_cata = [c1, c3]
    # a1.category.set(list_cata)
    #article.set(list)会把原有的catagory关系删除,替换成set中的新的list
    a2.category.set(list_cata)

    # c1.article_set.clear()
    # a1.category.clear()
    # 一。2、catagory 也可以添加article,或删除文章:
    # c2.article_set.add(a3,a1)
    # c2.article_set.remove(a2)

    # 二、新建catagory:   a1是既存,catagory是新增的,一般用于tag标签,输入就是添加
    # a1.category.create(level=1,title='新增加catagory')

    # 三、查询文章所有catagory,article里定义了catagory,所以直接.catagory
    cata = a1.category.all()
    # print(cata)

    # 四、catagory里没有定义article,所以用.article_set 来引用
    articles = c1.article_set.all()
    # print(articles)

    # 组合查询
    articles = Article.objects.filter(category__id=15)
    articles = Article.objects.filter(category=15)  # 与上面一样
    # print(articles)

    articles = Article.objects.filter(category__title__startswith='通知')
    articles = Article.objects.filter(category__title__startswith='通知').distinct()
    articles = Article.objects.filter(category__title__startswith='通知').distinct().count()
    # print(articles)

    catagorys = Category.objects.filter(article__title__startswith="尊师重教")
    print(catagorys)
    catagorys = Category.objects.filter(article__id=127)
    print(catagorys)
    catagorys = Category.objects.filter(article__id__in=[126, 127])  # 产生重复
    catagorys = Category.objects.filter(article__id__in=[126, 127]).distinct()  # 去掉重复
    print(catagorys)

    args = Article.objects.exclude(category=15)  # 查到的数据就很多了
    print(args)

 

posted @ 2023-09-15 10:26  花生与酒  阅读(9)  评论(0编辑  收藏  举报