Login

ManyToManyField that can be set even if it relies on a intermediary model.

Author:
quiesagua
Posted:
June 18, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Version of ManyToManyField that can be set even if it relies on a intermediary model.

 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
class IntermediatedManyToManyField(ManyToManyField):
    """
    ManyToManyField that can be set even if it relies on a intermediary model.
    
    """
    
    def contribute_to_class(self, cls, name):
        super(IntermediatedManyToManyField, self).contribute_to_class(cls, name)
        
        # Override the descriptor for the m2m relation
        setattr(
            cls,
            self.name,
            _ReverseIntermediatedManyRelatedObjectsDescriptor(self),
            )


class _ReverseIntermediatedManyRelatedObjectsDescriptor(
    ReverseManyRelatedObjectsDescriptor
    ):
    
    def __set__(self, instance, new_related_values):
        if instance is None:
            raise AttributeError('Manager must be accessed via instance')
        
        manager = self.__get__(instance)
        
        pre_existing_values = manager.all()
        
        new_related_value_pks = [
            new_related_value.pk for new_related_value in new_related_values]
        values_to_unrelate = pre_existing_values.exclude(
            pk__in=new_related_value_pks)
        values_to_unrelate.delete()
        
        # Create relationships for values not previously related, leaving alone
        # those which exist already
        intermediary_model = self.field.rel.through
        instance_field_name = manager.source_field_name
        related_field_name = manager.target_field_name
        for related_value in new_related_values:
            if related_value not in pre_existing_values:
                intermediary_model.objects.create(**{
                    instance_field_name: instance,
                    related_field_name: related_value,
                    })

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.