简体   繁体   English

如何将查询集添加到ManyToMany关系?

[英]How to add queryset to ManyToMany relationship?

I have following models: 我有以下型号:

class EnMovielist(models.Model):
    content_ID = models.CharField(max_length=30)
    release_date = models.CharField(max_length=30)
    running_time = models.CharField(max_length=10)
    actress = models.CharField(max_length=300)
    series = models.CharField(max_length=30)
    studio = models.CharField(max_length=30, null=True)
    director = models.CharField(max_length=30)

    def __str__(self):
        return self.content_ID


class EnActress(models.Model):
    name = models.CharField(max_length=100, null=True)
    movielist = models.ManyToManyField(EnMovielist, related_name='movies')

    def __str__(self):
        return self.name

I got error when I try to this in Django shell, 在Django Shell中尝试执行此操作时出现错误,

b = EnActress.objects.values_list('name', flat=True)
a = EnMovielist.objects.filter(actress__contains=b).values_list('content_ID')

b.movielist.add(a)



AttributeError: 'QuerySet' object has no attribute 'movielist'

How can I django queryset add into many-to-many field? django queryset如何添加到多对多字段? I have no idea why this is happening.. Any help appreciated! 我不知道为什么会这样。.任何帮助表示赞赏! :) :)

You should call m2m add from instance and adding entity should be also model instance. 您应该从实例调用m2m add ,添加实体也应该是模型实例。 Otherwise your expression doesn't make sense. 否则,您的表情就没有意义。

b = EnActress.objects.get(pk=some_pk) # get an instance, not queryset
a = EnMovielist.objects.get(pk=some_pk) # also instance
b.movielist.add(a)

You should not be using values_list if you intend to add a new relation afterwards. 如果您打算以后add新的关系,则不应使用values_list From the docs : 文档

values() and values_list() are both intended as optimizations for a specific use case: retrieving a subset of data without the overhead of creating a model instance values()values_list()都旨在作为特定用例的优化:检索数据的子集, 而无需创建模型实例

[ Emphasis mine ] [ 重点矿 ]

It's hard to tell what you're up to without having a good description of what you want to achieve. 如果没有对要实现的目标的充分描述,很难说出自己的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM