我有一个 Gun 模型,每把枪都有多个 Loads
我想要做的是向枪 GET 请求对象添加一个负载计数,但不在它自己的模型中。因此,当我执行 GET 请求时,计数就完成了,如果可能的话,只针对 GET 请求。否则我可以让 POST load_count = 0,因为没有这样的字段,它不应该被保存。
class Gun(models.Model):
name = models.CharField(max_length=128)
class Load(models.Model):
gun = models.ForeignKey(Gun, related_name='gun')
foo = ...
序列化器:
class GunSerializer(serializers.HyperlinkedModelSerializer):
??? load_count = Field() -- reverse lookup and count loads
id = serializers.Field()
class Meta:
model = Gun
fields = ('id',"name", ???? "load_count")
class LoadSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field()
class Meta:
model = Load