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
Tags:
field related manytomany
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. ManyToManyField no syncdb by powerfox 6 years, 7 months ago
  2. (Almost) Single table polymorphism in Django by julkiewicz 4 years, 4 months ago
  3. Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages by EmilStenstrom 4 years, 11 months ago
  4. Fix for the bad behaviour of GenericForeignKey field by pinkeen 4 years, 8 months ago
  5. unique_together with many to many fields by j4nu5 3 years, 11 months ago

Comments

Please login first before commenting.