[Django]-Django "can't set attribute" in model

52πŸ‘

βœ…

The problem was a name clash.

Apparently when querying the DB I had:

objs = MyReport.objects.annotate(location=F('test__location'))

This added location to the objects (didn’t see it in __dict__, but maybe I just missed it). This means I could give up the property since I could call report_instance.location. Of course, this means that all places that access MyReport I need to add the annotation (a special manager?).

πŸ‘€mibm

4πŸ‘

Just had a similar problem that seemed to be resolved by making sure I didn’t annotate with an alias that was the same name as the property I was trying to call.

πŸ‘€GSchriver

3πŸ‘

Add a setter method and the MyReport.location will be able to be set.

class MyReport(models.Model):
    group_id    = models.PositiveIntegerField(blank=False, null=False)
    test        = models.ForeignKey(Test, on_delete=models.CASCADE)
    owner       = models.ForeignKey(User, editable=False, default=get_current_user, on_delete=models.CASCADE)

    user_objects = UserFilterManager()


    _location = None

    @property
    def location(self):
        if self._location is not None:
            return self._location
        return self.test.location

    @location.setter
    def location(self, value):
        self._location = value

πŸ‘€mazurekt

-1πŸ‘

Try to ensure that test is set:

 @property
 def location(self):
     return self.test.location if self.test else None

Leave a comment