3

我正在尝试使用多对多字段制作应用程序。我写它并且不会尝试它。所以,我启动了 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

可以请人帮助我吗?

4

1 回答 1

9

您必须先创建 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/

于 2013-08-15T22:11:20.950 回答