在 django rest 框架中访问算术的外键属性

Posted

技术标签:

【中文标题】在 django rest 框架中访问算术的外键属性【英文标题】:Accessing foreign key attributes for arithmetics in django rest framework 【发布时间】:2022-01-20 18:58:01 【问题描述】:

我正在尝试计算房屋相对于一些相邻社区的长度,例如,house_size / (neighborhood[0].length + neighbor[1].length...):

class House(models.Model):
    house_id = models.CharField(max_length=256, primary_key=True)                             
    size = models.IntegerField()
    neighborhood = models.ManyToManyField('neighborhood', through='HouseNeighborhoodLink')
class Neighborhood(models.Model):
    length = models.IntegerField() 

我创建了一个表格来为几个社区分配一所房子。此外,房屋可以分配到几个相邻的社区:

class HouseNeighborhoodLink(models.Model):
    house = models.ForeignKey(House, on_delete=models.DO_NOTHING)
    neighborhood = models.ForeignKey(Neighborhood, on_delete=models.DO_NOTHING)

序列化器:

class LengthFromNeighborhoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Neighborhood
        fields = ['length']        


class HouseCoverageOfNeighborhood(serializers.ModelSerializer):
    Neighborhood = LengthFromNeighborhoodSerializer(read_only=True)

    class Meta:
        model = HouseNeighborhoodLink
        fields = ['house_id', 'Neighborhood']

我被困在三个点 (...) 中,我想在其中访问所有社区的长度属性,然后计算与房子的比例。我不确定如何从 HouseNeighborhoodLink 表中访问每个社区的长度:

class HouseCoverageDetail(generics.ListAPIView):
    queryset = HouseNeighborhoodLink.objects.all()
    serializer_class = HouseCoverageOfNeighborhood

    def get_queryset(self):
        house_id = self.kwargs['house_id']
        neighborhood = self.queryset.filter(house_id=house_id)
        ...
        return result

【问题讨论】:

【参考方案1】:

试试这个

 class HouseCoverageOfNeighborhood(serializers.ModelSerializer):
    Neighborhood = LengthFromNeighborhoodSerializer(many=True,read_only=True)

    class Meta:
        model = HouseNeighborhoodLink
        fields = ['house_id', 'Neighborhood']

【讨论】:

当我添加 many=True 时,我得到“Neighborhood object is not iterable”

以上是关于在 django rest 框架中访问算术的外键属性的主要内容,如果未能解决你的问题,请参考以下文章

如何处理 django-rest-framework 中 url 模式中的外键关系

Django REST Framework 中的外键值

django-rest-framework:如何更新嵌套的外键?我的更新方法甚至没有被调用

Django Rest API,如何为 2 个模型条目创建 post api,并具有与模型关联的外键

如何从 Django 模板中的外键访问值

如何使用 django rest 框架保存多对多字段对象