如何从自定义字段模型中获取所有字段?附Django相关代码示例
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
Companiesmodel) - The
managersfield will return a list of User objects, each with the fields you defined inUsersInCompanySerializer
内容的提问来源于stack exchange,提问作者nesalexy

