DRF - 带有直通模型的m2m字段的嵌套序列化

时间:2017-05-25 19:00:49

标签: python django m2m django-rest-framework

我在DRF中使用带有直通模型的m2m字段。一切都运行正常,除了我尝试嵌套会员序列化器。

models.py

class SweepStakes(models.Model):                                                          
    name = models.CharField(max_length=255)                                      

class Event(models.Model):                                                                       
    sweepstakes = models.ManyToManyField(SweepStakes, through='EventSweepStakesMembership')

class EventSweepStakesMembership(models.Model):                                  
    event = models.ForeignKey(Event, on_delete=models.CASCADE)                   
    sweepstakes = models.ForeignKey(SweepStakes, on_delete=models.CASCADE)       
    enabled = models.BooleanField(default=False)

serializers.py

class EventSweepStakesSerializer(serializers.ModelSerializer):                      
    name = serializers.ReadOnlyField(source='sweepstakes.name')                     

    class Meta:                                                                     
        model = EventSweepStakesMembership                                          
        fields = ('name', 'enabled',)

class EventSerializer(BaseTenantSerializer):                                                                     
    sweepstakes = EventSweepStakesSerializer(many=True, read_only=True)             

    class Meta:                                                                     
        model = Event                                                               
        fields = ('sweepstakes',)

此时,如果我将EventSweepStakesMembership模型和EventSweepStakesSerializer挂钩到视图中,我会得到我期望的结果,输出如下:

{"name": "thingy", "enabled" true}

但是,当我将Event模型和EventSerializer序列化程序挂钩到视图中时,sweepstakes字段将返回一个空字典而不是嵌套表示,如下所示:

{"sweepstakes": [{}]}

请注意,它不是一个空数组,换句话说,它确实会看到相关的直通模型,但在显示时却没有正确地序列化它。

没有错误,它只是空的。我试过增加depth序列化程序的Event无效。

我是否遗漏了某些东西,或者甚至可能都错了?

谢谢!

1 个答案:

答案 0 :(得分:2)

知道了,感谢这个答案:

https://stackoverflow.com/a/17263583/1366989

此处缺少的元素是source上的EventSerializer kwarg。所以,它现在看起来像这样,并按预期工作:

class EventSerializer(BaseTenantSerializer):                                                                
    sweepstakes = EventSweepStakesSerializer(                                    
        source='eventsweepstakesmembership_set', many=True, read_only=True       
    )