Django Rest框架工作中的多对多关系

时间:2018-09-29 08:59:33

标签: python django python-3.x django-rest-framework postman

我有一个问题,需要了解django rest框架文档的多对多关系,并上传图像之类的文件,这是我的代码。

models.py

class Team(models.Model):
    admin = models.ForeignKey(User, null=True, blank=True, related_name='admin', on_delete=models.CASCADE)
    name = models.CharField(blank=True, max_length=100)
    longitude = models.FloatField(blank=True, null=True, max_length=20)
    latitude = models.FloatField(blank=True, null=True, max_length=20)
    score = models.IntegerField(blank=True, null=True, default=0)
    country = models.ForeignKey(Country, blank=True, on_delete=models.DO_NOTHING)
    city = models.ForeignKey(City, blank=True, on_delete=models.DO_NOTHING)
    players = models.ManyToManyField(User, blank=True, related_name='players')
    created = models.DateField(auto_now_add=True)


class TeamImage(models.Model):
    Team = models.ForeignKey(to=Team, null=True, blank=True, on_delete=models.CASCADE)
    img = models.ImageField(upload_to='team_img/', null=True, blank=True)

serializer.py

class TeamCreateSerializer(ModelSerializer):
    # admin = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),
    # many=False, default=serializers.CurrentUserDefault())
    players = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True)
    country = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all())
    city = serializers.PrimaryKeyRelatedField(queryset=City.objects.all())
    score = serializers.IntegerField(read_only=True)
    images = TaskImageSerializer(source='teamimage_set', many=True, read_only=False)
# images = TaskImageSerializer(many=True, read_only=True)

class Meta:
    model = Team
    fields = [
        # 'admin',
        'name',
        'longitude',
        'latitude',
        'score',
        'country',
        'city',
        'players',
        'created',
        'images',
    ]

def create(self, validated_data):
    images_data = self.context.get('view').request.FILES
    team = Team.objects.create(name=validated_data.get('name', 'no-title'),
                               latitude=validated_data.get('latitude'),
                               longitude=validated_data.get('longitude'),
                               # score=validated_data.get('score'),
                               country=validated_data.get('country'),
                               city=validated_data.get('city'),
                               # players=validated_data.get('players'),
                               created=validated_data.get('created'),
                               # images=validated_data.get('images'),
                               )
    for image_data in images_data.values():
        TeamImage.objects.create(task=team, image=image_data)
    return team

view.py

class TeamAPIView(ListCreateAPIView):
    queryset = Team.objects.all()
    serializer_class = TeamCreateSerializer
    permission_classes = [AllowAny, AllowAnonymous]
    pagination_class = ProfileLimitPagination

    def perform_create(self, serializer):
        serializer.save(admin=self.request.user)

我想做的是将存在的玩家记录设置为多对多,并向团队添加图像。但是最后一个代码无法正常工作,我留下了注释行,因为这些注释是我的尝试。

最后一个API应该是

 {
        "name": "team1",
        "longitude": 12,
        "latitude": 12,
        "score": 0,
        "country": 2,
        "city": 1,
        "players": [],
        "created": "2018-09-26",
        "images": []
  }

那么我的问题是什么以及如何解决它,我阅读了django-rest-framework文档,但我没有明白我的意思,所以任何机构都有解决方案,请帮助我。

最后,当我想更新播放器或管理员等任何值或上传新图像时,我该怎么办?

很抱歉发表了很长的帖子,但是我想让任何人都清楚阅读它。

0 个答案:

没有答案