I have three models of the player, team, and membership, where the player and team have a many-to-many relationship, using membership as an intermediate model.
class Player(models.Model): name = models.CharField(max_length=254) rating = models.FloatField(null=True) install_ts = models.DateTimeField(auto_now_add=True, blank=True) update_ts = models.DateTimeField(auto_now_add=True, blank=True) class Team(models.Model): name = models.CharField(max_length=254) rating = models.FloatField(null=True) players = models.ManyToManyField( Player, through='Membership', through_fields=('team', 'player')) is_active = models.BooleanField(default=True) install_ts = models.DateTimeField(auto_now_add=True, blank=True) update_ts = models.DateTimeField(auto_now_add=True, blank=True) class Membership(models.Model): team = models.ForeignKey('Team') player = models.ForeignKey('Player')
Now I needed to renew this membership using the django rest framework. I tried updating them using Writable nested serializers by writing a custom .update() command serializer.
@transaction.atomic def update(self, instance, validated_data): ''' Cutomize the update function for the serializer to update the related_field values. ''' if 'memberships' in validated_data: instance = self._update_membership(instance, validated_data)
Now this works well for updating the values ββin the database for the membership table. The only problem I am facing is that I cannot update the preloaded instance in memory, which, at the request of PATCH for this API, updates the values ββin the database, but the API response shows stale data.
The following GET request for the same resource gives updated data. Anyone who has worked with the many-to-many relationship in django and written their own update / create methods for writeable nested serializers can help me understand a possible way to solve this problem.
django django-orm django-rest-framework
Manjit kumar
source share