Django ManyToManyField内部的过滤结果 [英] Django Filtering results inside ManyToManyField

查看:42
本文介绍了Django ManyToManyField内部的过滤结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序列化之前,我需要过滤ManyToManyField的结果.

I need to filter the results of a ManyToManyField before serializing it.

示例:

仅当记录主体个人"的授权程序"未通过"expiration_date"时,用户才应查看记录的详细信息.

A user should see details on a record only if 'expiration_date' hasn't passed for 'Authorized Program' on file for the 'Individual' who is the subject of the record.

我的模型和序列化程序当前显示所有相关的授权程序"记录的列表.

My model and serializer currently show a list of ALL related Authorized Program records.

问题:

在作为父个人"记录中的列表返回之前,如何将该列表过滤为仅未过期的记录?

注意:这不是有关基于M2M字段过滤父查询集的问题.这是关于在返回父对象之前过滤M2M字段的内容.

当前,序列化程序仅跳过"active_authorized_program_list"字段.

Currently, the serializer simply skips the 'active_authorized_program_list' field.

class Individual(models.Model):
    name = models.CharField(max_length=128, blank=True, default='')
    dob = models.DateField(null=True)
    authorized_program_list = models.ManyToManyField(
        'Program',
        related_name='individual_authorized_program_list',
        through='ReleaseAuthorization',
        blank=True
    )

    @property
    def current_age(self):
        if self.dob:
            today = datetime.date.today()
            return (today.year - self.dob.year) - int(
                (today.month, today.day) <
                (self.dob.month, self.dob.day))
        else:
            return 'Unknown'

    @property
    def active_authorized_program_list(self):
        return (
            self
                .authorized_program_list
                .get_queryset()
                .filter(expiration_date__lte=datetime.Date())
        )

class Program(models.Model):
    name = models.CharField(max_length=128, blank=True, default='')
    individual_list = models.ManyToManyField(
        'individual.Individual',
        related_name='program_individual_list',
        through='hub_program.ReleaseAuthorization',
        blank=True
    )
    active = models.BooleanField(default=True)

class ReleaseAuthorization(models.Model):
    individual = models.ForeignKey(
        Individual,
        related_name="release_authorization_individual",
        on_delete=models.CASCADE
    )
    program = models.ForeignKey(
        Program,
        related_name="release_authorization_program",
        on_delete=models.CASCADE
    )
    expiration_date = models.DateField()


class IndividualSerializer(serializers.ModelSerializer):
    class Meta:
        model = Individual
        fields = (
            'name',
            'dob',
            'current_age',
            'authorized_program_list',
            'active_authorized_program_list',
        )

序列化结果缺少'active_authorized_program_list'的最后一行:

Serialized Result is missing the last line for 'active_authorized_program_list':

{
    "name": "Individual One",
    "dob": "1974-10-11",
    "current_age": 43,
    "authorized_program_list": [1,2,3]
}

还应该具有:

"active_authorized_program_list": [1,2]

推荐答案

尝试在序列化程序中将字段类型指定为 PrimaryKeyRelatedField :

Try to specify type of field in serializer as PrimaryKeyRelatedField:

class IndividualSerializer(serializers.ModelSerializer):
    active_authorized_program_list = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Individual
        fields = (
            'name',
            'dob',
            'current_age',
            'authorized_program_list',
            'active_authorized_program_list',
        )

您还可以直接使用 在序列化器中生成列表SerializerMethodField :

Also you can generate list in serializer directly using SerializerMethodField:

class IndividualSerializer(serializers.ModelSerializer):
    active_authorized_program_list = SerializerMethodField()

    class Meta:
        model = Individual
        fields = (
            'name',
            'dob',
            'current_age',
            'authorized_program_list',
            'active_authorized_program_list',
        )

    def get_active_authorized_program_list(self, obj):
        return (
            self
            .authorized_program_list
            .filter(expiration_date__lte=datetime.Date()).values_list('id', flat=True)
         )

这篇关于Django ManyToManyField内部的过滤结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆