我有一个枪型,每支枪有多个载荷
我想要做的是向枪支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
答案 0 :(得分:2)
尝试使用IntegerField作为设置计数:
class GunSerializer(serializers.HyperlinkedModelSerializer):
load_count = serializers.IntegerField(source='load_set.count')
class Meta:
model = Gun
fields = ('id', "name", "load_count")
但是,您在加载模型中使用related_name
gun
我建议更改为loads
(或者只是省略然后使用默认load_set
和上面的例子将起作用)。如果要保留相关名称gun
,请将load_count序列化程序字段定义为:
load_count = serializers.IntegerField(source='gun.count')