Save multiple data using loops in django models using save function with admin save button [duplicate]

房东的猫 提交于 2019-12-13 03:57:03

问题


I'm trying to save data in loops from django admin. As i press it should save in database with same argument except one field which will have different value in each row.

class DealersList(models.Model):
    dealers_company = models.CharField(unique=True,max_length=100)
    concern_district = models.CharField(max_length=25, choices=CITY_CHOICES, default=False)
    address = models.CharField(max_length=50)
    vdc = models.CharField(max_length=30)
    contact_person = models.CharField(max_length=50,blank=True)
    phone_number = models.CharField(max_length=14,blank=True)
    email = models.EmailField(max_length=70,blank=True, null= True, unique= True)

And my SimDetail class which will have save() function contains a ForeignKey too

class SimDetail(models.Model):
    mobile_no = models.BigIntegerField("Mobile Number",unique=True)
    number_of_sim = models.IntegerField()
    agent = models.ForeignKey('DealersList',on_delete=models.CASCADE,to_field='dealers_company')
    sim_activation_date = models.DateField(auto_now=False, auto_now_add=False)
    submission_date = models.DateField(auto_now=False, auto_now_add=False)
    remarks = models.TextField(null=True,blank=True,validators=[MaxLengthValidator(200)])

    def save(self,*args, **kwargs):   
        ite=0
        for x in xrange(0,self.number_of_sim):
            self.mobile_no=self.mobile_no+ite
            ite=1
        super(SimDetail, self).save(*args, **kwargs)

Currently it's only saving last data which i think(i may be wrong) might being replaced again and again so at last it only stores the last value.

Can anyone help me, i'm trying to use it from admin only without using forms.


回答1:


All i needed to do was just put primary key to None so that a new object will be saved each time, i found my answer in this link



来源:https://stackoverflow.com/questions/45293833/save-multiple-data-using-loops-in-django-models-using-save-function-with-admin-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!