Search code examples
pythondjangomodels

How can I save an empty model (I only need it's pk created)


I have these 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))

And I need to make a form (inline form?) to create a new "Storage" that holds 2 "StorageType", but I don't know what to put in my forms.py because "Autofield" is not represented in the form.


Solution

  • "Storage" that holds 2 "StorageType"

    That means Storage can have many StorageType and StorageType can have Storages. Make a new ManyToMany Field in the storage.

    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))
    

    Then read Django Many-to-many relationships