如何保存空模型(我只需要它创建的pk)

时间:2015-05-07 14:53:11

标签: python django models

我有这些模特:

class Storage(models.Model):
    id = models.AutoField(primary_key=True)

    def __unicode__(self):
        return str(self.id)

class StorageType(models.Model):
    tripa = 'Tripa'
    portada = 'Portada'
    type_choice = (
        (tripa, 'Tripa'),
        (portada, 'Portada'),
    )
    sto_type = models.CharField(max_length=9, choices=type_choice, default=tripa)
    storage = models.ForeignKey(Storage)
    paper_type = models.ForeignKey(Paper)
    paper_qnty = models.IntegerField(blank=True, default=0)
    web_paper_qnty = models.IntegerField(blank=True, default=0)

    def __unicode__(self):
        return '%s of %s' %(self.sto_type, str(self.storage))

我需要创建一个表单(内联表单?)来创建一个新的"存储"它拥有2" StorageType"但我不知道在我的forms.py中放入什么因为" Autofield"没有在表格中表示。

1 个答案:

答案 0 :(得分:1)

  

"存储"它包含2" StorageType"

这意味着Storage可以有多个StorageTypeStorageType可以拥有存储空间。在存储中创建一个新的ManyToMany字段。

class Storage(models.Model):
    storage_types = models.ManyToManyField(StorageType)

    def __unicode__(self):
        return str(self.id)

class StorageType(models.Model):
    tripa = 'Tripa'
    portada = 'Portada'
    type_choice = (
        (tripa, 'Tripa'),
        (portada, 'Portada'),
    )
    sto_type = models.CharField(max_length=9, choices=type_choice, default=tripa)
    paper_type = models.ForeignKey(Paper)
    paper_qnty = models.IntegerField(blank=True, default=0)
    web_paper_qnty = models.IntegerField(blank=True, default=0)

    def __unicode__(self):
        return '%s of %s' %(self.sto_type, str(self.storage))

然后阅读Django Many-to-many relationships