netzkolchose / django-computedfields

Provides autogenerated autoupdated database fields for model methods.
MIT License
94 stars 14 forks source link

M2M through #151

Open stygmate opened 3 months ago

stygmate commented 3 months ago

i'm in the case of computed field depending on fields on a model on the otherside of M2M relation and also of fields in intermediate model. (I have followed the documentation example)

updates are ok in all cases i tested except when doing: person.groups.add(group) Meanwhile person.groups.remove(group) works. ( I suspect delete signal to be triggered in the case of remove but nothing other than m2m signal in the case of add )

any elegant solution to handle that without adding groups in depends (which trigger more updates than necessary) ?

excerpt from doc example for reference:

class Person(ComputedFieldsModel):
    name = models.CharField(max_length=32)

    @computed(models.CharField(max_length=256),
        depends=[
            ('memberships', ['joined_at']),
            ('memberships.group', ['name'])         # replaces groups.name dep
        ],
        prefetch_related=['memberships__group']
    )
    def groupjoins(self):
        if not self.pk:
            return ''
        names = []
        for membership in self.memberships.all():   # not using groups anymore
            names.append('{}: joined at {}'.format(
                membership.group.name, membership.joined_at))
        return ','.join(names)

class Group(models.Model):
    name = models.CharField(max_length=32)
    members = models.ManyToManyField(Person, related_name='groups', through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person, related_name='memberships')
    group = models.ForeignKey(Group, related_name='memberships')
    joined_at = SomeDateField(...)