Python,Django - ValueError:“< ...>”在可以使用多对多关系之前,需要为字段“...”设置值

时间:2017-01-17 15:49:57

标签: python django manytomanyfield m2m

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

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

我的models.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字段的正确值。

1 个答案:

答案 0 :(得分: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