Home > Software design >  How to append value to the ArrayField in Django with PostgreSQL?
How to append value to the ArrayField in Django with PostgreSQL?

Time:06-25

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?

CodePudding user response:

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.time.append(attendance.timestamp.time())
attend.save()

CodePudding user response:

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()
  • Related