Passed
Push — master ( 5ba9be...1ef026 )
by Swen
01:55
created

  A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
dl 0
loc 50
rs 10
c 0
b 0
f 0
ccs 24
cts 26
cp 0.9231
wmc 11

2 Methods

Rating   Name   Duplication   Size   Complexity  
B ocalizedModel.__init__() 0 22 5
B ocalizedModel.save() 0 21 6
1 1
from django.db import models, transaction
2 1
from django.db.utils import IntegrityError
3
4 1
from .fields import LocalizedField
5 1
from .localized_value import LocalizedValue
6
7
8 1
class LocalizedModel(models.Model):
9
    """A model that contains localized fields."""
10
11 1
    class Meta:
12 1
        abstract = True
13
14 1
    def __init__(self, *args, **kwargs):
15
        """Initializes a new instance of :see:LocalizedModel.
16
17
        Here we set all the fields that are of :see:LocalizedField
18
        to an instance of :see:LocalizedValue in case they are none
19
        so that the user doesn't explicitely have to do so."""
20
21 1
        super(LocalizedModel, self).__init__(*args, **kwargs)
22
23 1
        for field in self._meta.get_fields():
24 1
            if not isinstance(field, LocalizedField):
25 1
                continue
26
27 1
            value = getattr(self, field.name, None)
28
29 1
            if not isinstance(value, LocalizedValue):
30 1
                if isinstance(value, dict):
31 1
                    value = LocalizedValue(value)
32
                else:
33 1
                    value = LocalizedValue()
34
35 1
            setattr(self, field.name, value)
36
37 1
    def save(self, *args, **kwargs):
38
        """Saves this model instance to the database."""
39
40 1
        if not hasattr(self, 'retries'):
41 1
            self.retries = 0
0 ignored issues
show
Coding Style introduced by
The attribute retries was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
42
43 1
        with transaction.atomic():
44 1
            try:
45 1
                return super(LocalizedModel, self).save(*args, **kwargs)
46 1
            except IntegrityError as ex:
47
                # this is as retarded as it looks, there's no
48
                # way we can put the retry logic inside the slug
49
                # field class... we can also not only catch exceptions
50
                # that apply to slug fields... so yea.. this is as
51
                # retarded as it gets... i am sorry :(
52 1
                if 'slug' not in str(ex):
53
                    if self.retries >= 100:
54
                        raise ex
55
56 1
        self.retries += 1
57
        return self.save()
58