Decoupling models with cross-database relations

 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
class DecoupledModel(models.Model):

    class Meta:
        abstract = True

    _linked_fields = {
        # 'field': MyModel,
    }

    def __getattr__(self, name):
        fields = self.__class__._linked_fields
        if name in fields:
            model_class = fields[name]
            model = None
            try:
                pk = getattr(self, name + '_id')
                if pk:
                    model = model_class.objects.get(pk = pk)
            except:
                pass
            self.__dict__[name] = model
            return model
        else:
            return super(DecoupledModel, self).__getattribute__(name)

    def __setattr__(self, name, value):
        fields = self.__class__._linked_fields
        if name in fields:
            pk = 0
            try:
                if value:
                    pk = value.pk
            except:
                pass
            self.__dict__[name + '_id'] = pk
            self.__dict__[name] = value
            return pk
        else:
            return super(DecoupledModel, self).__setattr__(name, value)

More like this

  1. Allow filtering and ordering by counts of related query results by exogen 6 years, 1 month ago
  2. Manager for something like __inall by apollo13 5 years, 6 months ago
  3. Export Related as JSON Admin Action by johnboxall 3 years, 10 months ago
  4. EditInline for GenericForeignKey by king 5 years ago
  5. Make hyperlinks for labels of raw_id_fields (jQuery) by ramen 3 years, 4 months ago

Comments

(Forgotten your password?)