Skip to main content
 首页 » 编程设计

" needs to have a value for field "..." before this many-to-many relationship can be used" rel="bookmark">Python、Django之ValueError : "...>" needs to have a value for field "..." before this many-to-many relationship can be used

2025年02月15日2998°冷暖

亲爱的 StackOverflow 社区。 我的问题与将新记录插入到包含 many2many fields 字段的表有关。

我花了一整天的时间尝试自己解决这个问题,阅读 django 文档并在 stackoverflow 中冲浪。

我的模型.py:

from django.db import models 
from django_extensions.db.models import TimeStampedModel 
 
 
class clans(TimeStampedModel): 
    rfam_acc = models.CharField(max_length=7) 
    rfam_id = models.CharField(max_length=40) 
    description = models.CharField(max_length=100) 
    author = models.CharField(max_length=100) 
    comment = models.CharField(max_length=2000, null=True) 
 
    class Meta: 
        ordering = ('rfam_id',) 
 
    def __str__(self): 
        return self.rfam_id 
 
 
class families(TimeStampedModel): 
    rfam_acc = models.CharField(max_length=7) 
    rfam_id = models.CharField(max_length=40) 
    description = models.CharField(max_length=75) 
    author = models.CharField(max_length=100) 
    clan = models.ManyToManyField(clans, null=True, blank=True) 
    comment = models.CharField(max_length=2000, null=True) 

我的数据收集脚本(来自另一个数据库)和在我的数据库中的插入:(这是从 manage.py shell_plus 运行的)。

import mysql.connector 
from browse.models import clans, families 
 
 
def run(): 
 
    #... Query from another DB  
 
    # Query for clans using cursor. assign results to list of lists row_clans 
    query_clans = ("SELECT c.clan_acc, c.id, c.description, c.author, c.comment FROM clan c") 
    cursor_clans.execute(query_clans) 
    row_clans = cursor_clans.fetchall() 
# Creation of entry clans in the database. 
    for clan in row_clans: 
        clap = clans.objects.create( 
                rfam_acc=clan[0], 
                rfam_id=clan[1], 
                description=clan[2], 
                author=clan[3], 
                comment=clan[4], 
                ) 
# Query for families, that have clan = just created clan. Result in a list of lists row_family. 
        query_families = ("SELECT f.rfam_acc, f.rfam_id, f.description, f.author, f.comment, c.id FROM clan_membership cm, family f, clan c WHERE f.rfam_acc = cm.rfam_acc AND cm.clan_acc = c.clan_acc AND c.id =") 
        cursor_families.execute(query_families + "\"" + clan[1] + "\"") 
        row_family = cursor_families.fetchall() 
# Creation of entryes families in the database. 
        for family in row_family: 
            families.objects.create( 
                    rfam_acc=family[0], 
                    rfam_id=family[1], 
                    description=family[2], 
                    author=family[3], 
                    comment=family[4], 
                    clan=clan[1] 
                    ) 
            print ("insert family ", family[1], " in ", clan[1]) 
 
# close the cursors and close the connection to the server 
    cursor_clans.close() 
    cursor_families.close() 
    cnx.close() 

最后是 shell 中的错误:

Traceback (most recent call last): 
  File "<console>", line 1, in <module> 
  File         "/Users/work/Desktop/StructuRNA/website/scripts/SQLfromRfamIntoClansFamily.py", line 42, in run 
clan=clan[1] 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method 
return getattr(self.get_queryset(), name)(*args, **kwargs) 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/query.py", line 397, in create 
obj = self.model(**kwargs) 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/base.py", line 550, in __init__ 
setattr(self, prop, kwargs[prop]) 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__ 
    manager = self.__get__(instance) 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__ 
return self.related_manager_cls(instance) 
  File "/Users/work/Desktop/StructuRNA/.VirEnvStructuRna/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 783, in      __init__ 
   (instance, self.source_field_name)) 
 ValueError: "<families: families object>" needs to have a value for field "families" before this many-to-many relationship can be used. 

有什么帮助吗? 我不明白什么不起作用。

另一件有趣的事情是,在我的数据库中,我发现了第一个元素的插入(在我尝试运行脚本时重复了多次)。 该元素对于 m2m 字段也有其正确的值。

请您参考如下方法:

您需要先创建“家庭”对象的实例,然后才能向 ManyToManyField 添加条目

family = families.objects.create( 
    rfam_acc=family[0], 
    rfam_id=family[1], 
    description=family[2], 
    author=family[3], 
    comment=family[4] 
) 
 
family.clan.add(clan[1]) 

此外,您可能对 bulk_create 感兴趣:https://docs.djangoproject.com/en/1.10/ref/models/querysets/#bulk-create