【问题标题】:Python, Django - ValueError: "<...>" needs to have a value for field "..." before this many-to-many relationship can be usedPython,Django - ValueError:“<...>”需要为字段“...”提供一个值,然后才能使用这种多对多关系
【发布时间】:2017-06-01 18:32:15
【问题描述】:

尊敬的 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 字段也有其正确的值。

【问题讨论】:

    标签: python django manytomanyfield m2m


    【解决方案1】:

    您需要先创建“家庭”对象的实例,然后才能向 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

    【讨论】:

    • 非常感谢。这解决了我的问题。但我以完全不同的方式实现了这一点。 : cl = clans(.....attributes assignment..) cl.save() fa = family(.......attributes assignment..) fa.save() fa.clan.add(cl) fa .save() 另一个重要的一点是,当您添加 many2many 关系时,在我的例子中是氏族。 .add() 的参数应该是一个对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2023-03-24
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多