summaryrefslogtreecommitdiff
path: root/django/db/models/fields/structures.py
blob: b90164cc2822c89417d113dfca13ba1cfb4df643 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from django.core.exceptions import ValidationError
from django.db.models.loading import cache
from django.db.models.fields import Field
from django.db.models.fields.subclassing import SubfieldBase


class ListField(Field):
    __metaclass__ = SubfieldBase
    
    def __init__(self, field_type):
        self.field_type = field_type
        super(ListField, self).__init__(default=[])
    
    def get_prep_lookup(self, lookup_type, value):
        return self.field_type.get_prep_lookup(lookup_type, value)
    
    def get_db_prep_save(self, value, connection):
        return [
            self.field_type.get_db_prep_save(o, connection=connection)
            for o in value
        ]
    
    def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
        return self.field_type.get_db_prep_lookup(
            lookup_type, value, connection=connection, prepared=prepared
        )
    
    def to_python(self, value):
        try:
            value = iter(value)
        except TypeError:
            raise ValidationError("Value should be iterable")
        return [
            self.field_type.to_python(v)
            for v in value
        ]


class EmbeddedModel(Field):
    __metaclass__ = SubfieldBase
    
    def __init__(self, to):
        self.to = to
        super(EmbeddedModel, self).__init__()
    
    def get_db_prep_save(self, value, connection):
        data = {}
        if not isinstance(value, self.to):
            raise ValidationError("Value must be an instance of %s, got %s "
                "instead" % (self.to, value))
        if type(value) is not self.to:
            data["_cls"] = (value._meta.app_label, value._meta.object_name)
        for field in value._meta.fields:
            # If the field is a OneToOneField that makes the inheritance link,
            # ignore it.
            if field.rel and field.rel.parent_link:
                continue
            data[field.column] = field.get_db_prep_save(
                getattr(value, field.name), connection=connection
            )
        return data
    
    def to_python(self, value):
        if isinstance(value, self.to):
            return value
        try:
            value = dict(value)
        except TypeError:
            raise ValidationError("Value should be a dict")
        
        if "_cls" in value:
            cls = cache.get_model(*value.pop("_cls"))
        else:
            cls = self.to
        
        return cls(**value)