无法将对象添加到Django的多对多字段中

时间:2013-08-15 21:57:14

标签: django python-2.7 django-models many-to-many

我正在尝试使用多对多字段制作应用。而且我写它并且不会尝试它。所以,我开始shell并制作一些对象,我得到了这个错误。

>>> mzz.controlsOrganization.add(org1, org2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 848, in __get__
through=self.field.rel.through,
  File "/home/fdobrovolny/virtualenv/first/lib/python2.7/site-packages/django/db/models/fields/related.py", line 538, in __init__
(instance, source_field_name))
ValueError: "<MZZ: TEST 1>" needs to have a value for field "mzz" before this many-to-many relationship can be used.

MZZ课程:

class MZZ(models.Model):
    name = models.CharField(max_length=100)
    name.short_decription = u'Název MZZ'
    ident = models.CharField(max_length=45, unique=True)
    active = models.BooleanField()
    active.boolean = True
    kind = models.ForeignKey(kind)
    deliveryDate = models.DateField()
    stateAfterDelivery = models.CharField(max_length=200)
    dateOfCommissioning = models.DateField()
    prescribedParameters = models.CharField(max_length=200)
    responsibleStaff = models.ForeignKey(User)
    dateOfManufacture = models.DateField()
    manufacturer = models.ForeignKey(organization, related_name='manufacturer')
    type = models.CharField(max_length=50)
    serialNumber = models.CharField(max_length=80)
    frequencyOfControls = models.ForeignKey(controls_frequency)
    location = models.CharField(max_length=50)
    methodOfControls = models.CharField(max_length=100)
    controlsOrganization = models.ManyToManyField(organization, related_name='controlsOrganization')
    servisOrganization = models.ManyToManyField(organization, related_name='servisOrganization')

def __unicode__(self):
    return self.name'

组织班:

class organization(models.Model):
    name = models.CharField(max_length=200)
    adress = models.CharField(max_length=200)
    telephoneNumber = models.CharField(max_length=35)
    email = models.EmailField()

    def __unicode__(self):
        return self.name

可以请有人帮助我吗?

1 个答案:

答案 0 :(得分:8)

您必须首先创建MZZ对象并保存(),然后添加组织。

mzz = MZZ()  # create 
mzz.save()   # save()

o = organization()
o.save()

m.organization.add(o)  # add(o)

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/