如何将查询集添加到多对多关系?
How to add queryset to ManyToMany relationship?
我有以下型号:
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
我在 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'
如何将 django 查询集添加到多对多字段中?
我不知道为什么会这样。任何帮助表示赞赏! :)
您应该从实例调用 m2m add
并且添加实体也应该是模型实例。否则你的表达没有意义。
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)
如果您打算以后 add
建立新关系,则不应使用 values_list
。来自 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
[强调我的]
如果没有很好地描述你想要实现的目标,就很难说出你在做什么。
我有以下型号:
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
我在 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'
如何将 django 查询集添加到多对多字段中? 我不知道为什么会这样。任何帮助表示赞赏! :)
您应该从实例调用 m2m add
并且添加实体也应该是模型实例。否则你的表达没有意义。
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)
如果您打算以后 add
建立新关系,则不应使用 values_list
。来自 docs:
values()
andvalues_list()
are both intended as optimizations for a specific use case: retrieving a subset of data without the overhead of creating a model instance
[强调我的]
如果没有很好地描述你想要实现的目标,就很难说出你在做什么。