简体   繁体   中英

How to append value to the ArrayField in Django with PostgreSQL?

I have created a model with the ArrayField in Django Model. I am using PostgreSQL for the database. I want to create new rows in the database or update the existing rows. But I can not insert or append data to the ArrayField .

Model

class AttendanceModel(BaseModel):
    """
    Model to store employee's attendance data.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attendance_user')
    date = models.DateField()
    time = ArrayField(models.TimeField(), blank=True, null=True)

    class Meta:
        unique_together = [['user', 'date']]

    def __str__(self):
        return f'{self.user.username} - {self.date}'

View

attend, created = models.AttendanceModel.objects.get_or_create(user=fingerprint.user, date=attendance_date)

attend.time = attend.time.append(attendance.timestamp.time())

attend.save()

The time field does not being created or updated with the new value.

How can I do this?

attend.time = attend.time.append(attendance.timestamp.time())

Here the return value of list.append(...) is being assigned to attend.time , which is None , thus the attend.time is not getting updated.

Try this instead,

attend, created = models.AttendanceModel.objects.get_or_create(
    user=fingerprint.user, date=attendance_date
)

attend.save()

Following this Answer I did this.

from django.db.models import Func, F, Value
.
.
.
attend, created = models.AttendanceModel.objects.get_or_create(user=fingerprint.user, date=attendance_date)
attend.time = Func(F('time'), Value(attendance.timestamp.time()), function='array_append')
attend.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