0

I have ArrayField in model Company

models.py

class Company(models.Model):
    members = ArrayField(models.IntegerField(blank=True), blank=True)
    ...

serializers.py

class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('name', 'description', 'date_created', 'user', 'status', 'theme', 'members')
    ...

It return this JSON

    {
        "name": "Jeep",
        "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
        "date_created": "2020-07-20T21:27:28.586149Z",
        "user": 2,
        "status": 2,
        "theme": 3,
        "members": [
            1,
            2,
            3
        ]
    }
   ...

where field members contains user ids from User model. I want change this ids to User data objects by him id

...
        "members": [
            {"id" : 1, ...},
            {"id" : 2, ...},
            {"id" : 3, ...},
        ]
...
Bee Lance
  • 47
  • 1
  • 6

1 Answers1

0

Try this.

class CompanySerializer(serializers.ModelSerializer):
    members = serializers.SerializerMethodField()
    class Meta:
        model = Company
        fields = ('name', 'description', 'date_created', 'user', 'status', 'theme', 'members')

    def get_members(self, obj):
        users = User.objects.filter(id__in=obj.members)
        return UserSerializer(users, many=True).data
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Sagar Adhikari
  • 1,312
  • 1
  • 10
  • 17
  • Thanks! What is mean )? ***MultipleObjectsReturned at /api/company/ get() returned more than one User -- it returned 2! Request Method: GET Request URL: https://crm.wsofter.ru:8000/api/company/*** – Bee Lance Aug 01 '20 at 07:04
  • Oh, simple mistake. Use filter instead of get. Try updated code. – Sagar Adhikari Aug 01 '20 at 07:05
  • Hi, Sagar. please, tell me, how edit field **members**? ) I added new question by [link](https://stackoverflow.com/questions/63241552/i-cant-edit-one-field-in-my-django-rest-app) – Bee Lance Aug 05 '20 at 07:51
  • This adds a new query for each user, which can add up. Is there a way to avoid this? – Spirconi Jan 11 '22 at 12:31
  • @Spirconi, you can use query like this: User.objects.filter(...).values("id", "first_name", .........). – Sagar Adhikari Jan 11 '22 at 15:59