Opened 9 years ago

Closed 9 years ago

#25143 closed Bug (fixed)

ArrayField should implement from_db_value()

Reported by: Odahi Owned by: Tim Graham <timograham@…>
Component: contrib.postgres Version: 1.8
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description (last modified by Odahi)

I'm using a custom field with the new Postgres ArrayField:

class Tag(object):
   def __init__(self, id):
        self.id = id

   def __unicode__(self):
        return U"Tag(%d)" % self.id


class TagField(models.SmallIntegerField):
    # Dummy wrapper over SmallIntegerField.

   def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        return Tag(int(value))

   def get_prep_value(self, value):
        return value
   ...

# models.py

class Recommendation(models.Model):
    tags = ArrayField(TagField(), size=3)

    def __unicode__(self):
        return self.tags

Then

>>> Recommendation.objects.create(tags=[Tag(1), Tag(2)])
>>> Recommendation.objects.all()

[<Recommendation: [1, 2]>]  # WRONG

This is wrong because I got Integers instead of Tag objects:

[<Recommendation: [Tag(1), Tag(2)]>]  # OK

Looking at the ArrayField source code seems that to_python() is implemented but never called. I think from_db_value() should be also implemented.

Change History (11)

comment:1 by Odahi, 9 years ago

Description: modified (diff)

comment:2 by Tim Graham, 9 years ago

Can you propose a patch and regression test?

in reply to:  2 comment:3 by Odahi, 9 years ago

Replying to timgraham:

Can you propose a patch and regression test?

Hello Tim, never did it before, but I think I can submit a tentative patch & test for this in the next days. I'll try.

comment:4 by Odahi, 9 years ago

Has patch: set

I've just added a tentative patch. https://github.com/Odahi/django/tree/ticket_25143
Would be great if someone can check it.

Version 0, edited 9 years ago by Odahi (next)

comment:5 by Tim Graham, 9 years ago

Triage Stage: UnreviewedAccepted

comment:6 by Tim Graham, 9 years ago

Patch needs improvement: set

comment:7 by Tim Graham, 9 years ago

See #25579 for a related issue (querying on complex types) that could be fixed along with this.

comment:8 by Tim Graham, 9 years ago

Patch needs improvement: unset

comment:9 by Tim Graham, 9 years ago

Triage Stage: AcceptedReady for checkin

comment:10 by Tim Graham, 9 years ago

Patch needs improvement: set
Triage Stage: Ready for checkinAccepted

comment:11 by Tim Graham <timograham@…>, 9 years ago

Owner: set to Tim Graham <timograham@…>
Resolution: fixed
Status: newclosed

In 2495023:

Fixed #25143 -- Added ArrayField.from_db_value().

Thanks Karan Lyons for contributing to the patch.

Note: See TracTickets for help on using tickets.
Back to Top