简体   繁体   中英

How to populate django model via list

I have a model named student

class student(models.Model):
    stdname = models.CharField
    marks = models.CharField

    def __str__(self):
        return self.stdname

And I have a list named

    student_names=['xyz', 'zyx'...]

Now i want to populate the model's stdname with this list. How can i do this?

We can do this by using get_or_create method of object it will check for the name if it is not there it will create a stdname field and also if you want to add marks then use conditions as shown in below example.

for name in student_names:
    lt, created = student.objects.get_or_create(
        stdname=name,
    )
    if not created:
        lt.marks = <put your mark here>
    lt.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM