Skip to content
Advertisement

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?

Advertisement

Answer

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()
Advertisement