Home > Back-end >  Is it possible to save data directly to django without using forms?
Is it possible to save data directly to django without using forms?

Time:08-10

If I have a model like this:

class SomeClass(models.Model):
    title = models.CharField(max_length=100)
    field1 = models.FloatField()
    field2 = models.FloatField()
    field3 = models.FloatField()
    field4 = models.FloatField()
    field5 = models.FloatField()
    
    def __str__(self):
        return self.title

and I have a set of data, for example data_list = ('title', 10, 20, 30, 40, 50)

How can I save data directly without asking for input to user, or using forms?

thanks

CodePudding user response:

You have multiple options as specified in the Django Docs

One way to do it is:

some_obj = SomeClass(title="title", field1=10, field2=20, field3=30, field4=40, field5=50)
some_obj.save()

Using your data_list, you may do something like:

some_obj = SomeClass(title=data_list[0], field1=data_list[1], field2=data_list[2], field3=data_list[3], field4=data_list[4], field5=data_list[5])
some_obj.save()
  • Related