将文本添加到单元格而不覆盖现有数据

时间:2015-12-23 14:16:45

标签: python sql django

我目前正在使用一个Django项目。

我有字典:

来自models.py

class teltab(models.Model):
    code=models.CharField(max_length=255)
    telescope=models.CharField(max_length=255)
    comment=models.CharField(max_length=255,blank=True)

和一个向数据添加数据的表单:

class newtelescopesform(forms.ModelForm):
    class Meta:
        model=teltab

通常我会从表单中获得评论并将其写入字典:

来自views.py

if len(request.GET['comment'])>0:
                commentq=request.GET['comment']
                tel_list.update(comment=commentq)
                for item in tel_list: 
                    item.save()

但现在我需要在结果表中的已存在单元格中添加新注释。

即我的表格看起来像这样

Current table

我希望得到这个

Table of my dreams

2 个答案:

答案 0 :(得分:0)

  • 事实上,您要么使用 ForeignKey 定义新的评论模型:teltab
   class telTabModel(models.Model):
       code=models.CharField(max_length=255)
       telescope=models.CharField(max_length=255)

    class CommentModel(models.Model):
        teltab = models.ForeignKey('telTabModel', related_name='comments')
        # ...
    from django.contrib.postgres.fields import ArrayField

    class telTabModel(models.Model):
        code=models.CharField(max_length=255)
        telescope=models.CharField(max_length=255)
        comments = ArrayField(models.CharField(max_length=200), blank=True),
  • 如果你没有使用PosgreSQL而你仍想使用数组,我会推荐Jsonfield

    pip install jsonfield
    
    from jsonfield import JSONField

    class telTabModel(models.Model):
        code=models.CharField(max_length=255)
        telescope=models.CharField(max_length=255)
        comments = JSONField(default=[])

答案 1 :(得分:-1)

我想你应该将模型注释字段类型更改为TextField:

comment=models.TextField(blank=True)

然后只需添加" / n {new line}"它 编辑:Dan是对的,如果我没有弄错的话,在模型中存储列表并不是一个好主意。