Django Rest框架,如何使用foreignkey_id字段包含“ __all__”字段和相关字段

时间:2018-09-04 13:41:04

标签: python django django-rest-framework

这是我的文件- Models.py

class Model1(models.Model):
    user = models.ForeignKey(User)
    other_fields = models.CharField(max_length=40)

Serializers.py

class MySerializer(ModelSerializer):
    class Meta:
        model = Model1
        fields = '__all__'


Here  json request
{"user_id":1, "other_fields":"details"}

和views.py

serializer = MySerializer(data=request.data)
serializer.data

**Throws keyerror "user"**

当我尝试更改请求参数时     “ user_id”到“ user”对我有用。 但是我不能更改请求json。有什么方法可以在序列化程序中解决此问题?

我可以将所有字段都设置为“ _all _ ”,但是由于字段太多,这不是一个好的解决方案。

我也尝试过-

 class MySerializer(ModelSerializer):
    user = serializers.CharField(source='user_id')
    class Meta:
        model = Model1
        fields = '__all__'

但这对我不起作用。

3 个答案:

答案 0 :(得分:2)

我认为您正在使用viewset类进行查看。那就可以了


覆盖 __init__ 方法
class MySerializer(ModelSerializer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if 'view' in self.context and self.context['view'].action in ['create', 'update', 'partial_update']:
            self.fields['user_id'] = self.fields.pop('user')

    class Meta:
        model = Model1
        fields = '__all__'



['create', 'update', 'partial_update'] viewset 类的actions,它们表示 HTTP POST < / strong>, HTTP PUT HTTP PATCH

答案 1 :(得分:1)

尝试使用PrimaryKeyRelatedField

class MySerializer(ModelSerializer):

    def to_internal_value(self, data):
        data = data.copy() # incase request data is immutable
        data['user'] = data['user_id']
        return super().to_internal_value(data)

    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model = Model1
        fields = '__all__'

这应该允许有效载荷:

 {"user_id": 1, "other_fields": "details"}

答案 2 :(得分:1)

尝试一下:

library(ggplot2)
library(grid)
library(gtable)

grid.newpage()
p1 <- ggplot(ex, 
         aes(factor(subgroups, levels = c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 
                                          'Saturday', 'Sunday')),
             y_left)) + 
  geom_bar(fill = rgb(16/255, 72/255, 128/255), stat = 'identity') + 
  theme_bw() +
  labs(x = 'weekday')
p2 <- ggplot(ex, aes(factor(subgroups,
                              levels = c('Monday', 'Tuesday', 'Wednesday', 
                                         'Thursday', 'Friday', 'Saturday', 'Sunday')), y_right)) + 
  geom_line(colour = rgb(237/255, 165/255, 6/255), group = 1) + 
  geom_point(color = rgb(237/255, 165/255, 6/255), size = 3) +
  scale_y_continuous(limits = c(0, 180)) +
  labs(y = 'name for y_left axis') +
  theme_bw() %+replace% 
  theme(panel.background = element_rect(fill = NA))
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
                 pp$l, pp$b, pp$l)

# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

# draw it
grid.draw(g)