简体   繁体   English

组合两个或多个查询集或将不同模型组合为单个输出

[英]Combining two or more queryset or combining different models as a single output

I have created 2 models Images and UserDetails both contain a foreign key field of auth_user (User). 我创建了2个模型Images和UserDetails都包含auth_user (用户)的外键字段。 If I provide a user id, I want get data from 3 models. 如果提供用户ID,则要从3个模型中获取数据。 ie; from User, UserDetails and Images as queryset in DRF 从用户,用户详细信息和图像作为DRF中的查询集

models.py models.py

from django.contrib.auth.models import User
from django.db import models

class Images(models.Model):
    name = models.CharField(max_length=10)
    userid = models.ForeignKey(User,on_delete=models.CASCADE)
    category = models.CharField(max_length=10)
    file = models.FileField(blank=True, null=True)

class Categories(models.Model):
    name = models.CharField(max_length=15)

class Skills(models.Model):
    name = models.CharField(max_length=20)
    category = models.ManyToManyField(Categories)

class UserDetails(models.Model):
    userid = models.ForeignKey(User,on_delete=models.CASCADE)
    firebase = models.CharField(max_length=50)
    mobile = models.IntegerField()
    pin = models.IntegerField( null=True)
    latitude = models.CharField(max_length=50,null=True)
    longitude = models.CharField(max_length=50,null=True)
    profile_pic = models.ManyToManyField(Images,null=True)
    skill = models.ManyToManyField(Skills,null=True)
    is_freelancer = models.IntegerField()

serializer.py 序列化器

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Images
        fields = '__all__'

views.py views.py

class Profile(ListAPIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication,)
    serializer_class = ImageSerializer

    def get_queryset(self):
        img = Images.objects.filter(userid=self.request.user.id)
        return img

If I run this in postman I get 如果我在邮递员中运行它,我会得到

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 2,
            "name": "",
            "category": "profile pic",
            "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png",
            "userid": 14
        }
    ]
}

but I want output something like this 但我想输出这样的东西

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "image": {
                        "id": 2,
                        "name": "",
                        "category": "profile pic",
                        "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png",
                        "userid": 14
             },

            "User": {
                        "id": 2,
                        "username": "Jasir",
                        .
                        .
                        .
             },

             "Details": {

                        "mobile": 7736663588,
                        "palce": "Kerala",
                        .
                        .
                        .
             },

    ]
}

Something like this, how this can be done in efficient way? 这样的事情,如何有效地做到呢?

I tried raw query, also tried piping method but it works only for same model 我尝试了原始查询,也尝试了管道方法,但仅适用于相同模型

If i understand your need correctly you can use serializer.methodField() link and achieve your need. 如果我正确理解了您的需求,则可以使用serializer.methodField() 链接来实现您的需求。 For this we need two more serialzer named UserSerializer and UserDetailsSerializer . 为此,我们还需要两个名为UserSerializerUserDetailsSerializer序列化UserSerializer

So our serializers.py will be like this 所以我们的serializers.py会像这样

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetails
        fields = '__all__'



class ImageSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField()
    details = serializers.SerializerMethodField()
    class Meta:
        model = Images
        fields = '__all__'


    def get_user(self, obj):
        user_instance = User.objects.get(id=obj.userid)
        response = UserSerializer(user_instance)
        return response.data

    def get_details(self, obj):
        user_details = UserDetails.objects.get(userid=obj.userid)
        response = UserDetailsSerializer(user_details)
        return response.data

And you will get response like this 这样你会得到回应

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {

            "id": 2,
          "name": "",
      "category": "profile pic",
          "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png",
        "userid": 14


            "User": {
                        "id": 2,
                        "username": "Jasir",
                        .
                        .
                        .
             },

             "Details": {

                        "mobile": 7736663588,
                        "palce": "Kerala",
                        .
                        .
                        .
             },

    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM