我正在尝试在 Django 中为一个用户开发一个 10 行和 10 列(文本字段)模型,以便他可以通过表单添加数据。有没有办法让它动态化?将来我可能需要添加 50 行和 50 列。
我尝试手动完成,但要做的时间太长了
imageNo_1 = models.CharField(max_length=50,blank=True,null=True)img_desc_1 = models.CharField(max_length=500,blank=True,null=True)
img_desc_2 = models.CharField(max_length=500,blank=True,null=True)
img_desc_3 = models.CharField(max_length=500,blank=True,null=True)
img_desc_4 = models.CharField(max_length=500,blank=True,null=True)
img_desc_5 = models.CharField(max_length=500,blank=True,null=True)
img_desc_6 = models.CharField(max_length=500,blank=True,null=True)
img_desc_7 = models.CharField(max_length=500,blank=True,null=True)
img_desc_8 = models.CharField(max_length=500,blank=True,null=True)
img_desc_9 = models.CharField(max_length=500,blank=True,null=True)
img_desc_10 = models.CharField(max_length=500,blank=True,null=True)
.
.
.
img_alt_1 = models.CharField(max_length=500,blank=True,null=True)
img_alt_2 = models.CharField(max_length=500,blank=True,null=True)
img_alt_3 = models.CharField(max_length=500,blank=True,null=True)
img_alt_4 = models.CharField(max_length=500,blank=True,null=True)
img_alt_5 = models.CharField(max_length=500,blank=True,null=True)
img_alt_6 = models.CharField(max_length=500,blank=True,null=True)
img_alt_7 = models.CharField(max_length=500,blank=True,null=True)
img_alt_8 = models.CharField(max_length=500,blank=True,null=True)
img_alt_9 = models.CharField(max_length=500,blank=True,null=True)
img_alt_10 = models.CharField(max_length=500,blank=True,null=True)
我找到答案了:
对于范围 (1, 31) 中的第 30 行: locals()[f"imageNo_{rowthirty}"] = models.CharField(max_length=50,blank=True,null=True)
locals()[f"img_desc_{rowthirty}"] = models.CharField(max_length=500,blank=True,null=True)
locals()[f"img_alt_{rowthirty}"] = models.CharField(max_length=500,blank=True,null=True)