You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从自定义字段模型中获取所有字段?附Django相关代码示例

解决方案:在Django REST Framework中获取自定义模型的所有字段(含多对多关系)

Hey there! I see what you're trying to do—let's get your code sorted so you can fetch all fields from your Companies model, including the managers ManyToMany relationship with full User details instead of just primary keys.

First, let's fix the main issue in your code: your UsersInCompanySerializer has an incorrect inheritance. You can't inherit from both PrimaryKeyRelatedField and ModelSerializer—those are two different types of classes (one is a field, the other is a full serializer). Let's adjust that and build out the proper setup.

Step 1: Fix the User Serializer

Rewrite your UsersInCompanySerializer to only inherit from ModelSerializer—this lets you define exactly which User fields you want to include:

class UsersInCompanySerializer(serializers.ModelSerializer): 
    class Meta: 
        model = User 
        # List all the User fields you want to return for each manager
        fields = ('id', 'first_name', 'last_name', 'email', 'is_active', 'is_staff')

Step 2: Update the Companies Serializer

Next, modify your CompaniesSerializer to use this new User serializer for the managers field. This will replace the default primary key output with the full User details you specified. Also, use fields = '__all__' to automatically include all fields from your Companies model:

class CompaniesSerializer(serializers.ModelSerializer):
    # Use our custom serializer for the managers ManyToMany field
    # `many=True` because one company can have multiple managers
    # `read_only=True` keeps this field read-only for GET requests (adjust if you need write support)
    managers = UsersInCompanySerializer(many=True, read_only=True)

    class Meta:
        model = Companies
        # Include ALL fields from the Companies model
        fields = '__all__'
        # If you don't want every field, you can list them explicitly instead:
        # fields = ('id', 'name', 'address', 'managers', ...)

Optional: Add Write Support for Managers (If Needed)

If you want to allow creating/updating a Company and associating managers at the same time, you'll need to override the create (and update) method in the CompaniesSerializer, since ManyToMany relationships require extra handling:

class CompaniesSerializer(serializers.ModelSerializer):
    managers = UsersInCompanySerializer(many=True, read_only=False)

    class Meta:
        model = Companies
        fields = '__all__'

    def create(self, validated_data):
        # Pull out manager data first—we can't pass this directly to Companies.objects.create()
        managers_data = validated_data.pop('managers')
        # Create the Company instance with the remaining data
        company = Companies.objects.create(**validated_data)
        
        # Associate each manager with the new company
        # Note: This assumes the User instances already exist (adjust if you need to create new Users)
        for manager_data in managers_data:
            manager = User.objects.get(id=manager_data['id'])
            company.managers.add(manager)
        
        return company

How It Works

With this setup, when you hit your CompaniesList endpoint:

  • Each Company object will include all its own fields (from the Companies model)
  • The managers field will return a list of User objects, each with the fields you defined in UsersInCompanySerializer

内容的提问来源于stack exchange,提问作者nesalexy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:32:47