向单元格中添加文本而不覆盖现有的数据

2024-05-14 10:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在与一个Django项目。你知道吗

我有字典在里面:

从型号.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

通常我会从表单中得到一条注释并将其写到字典中:

从视图.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


Tags: pyget字典modelsrequestcommentitemlength
2条回答

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

comment=models.TextField(blank=True)

然后只需添加“/n{newline}” 编辑:丹是对的,这不是一个好主意,如果我没弄错的话,有机会在模型中存储列表。你知道吗

  • 事实上,要么用一个外键定义新的注释模型: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,但仍然想使用array,我建议您使用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=[])

相关问题 更多 >

    热门问题