Django Rest-framework M2M 连接序列化与直通表

问题描述 投票:0回答:1

我有以下表格:

from django.db import models
from django.contrib.auth.models import AbstractUser
class Human(models.Model):
    _id = models.BigAutoField(primary_key=True)
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    image = models.ImageField(upload_to="pfpHuman", default="placeholderHuman.png")
    skills = models.JSONField(default=dict, blank=True)
    is_active = models.BooleanField(default=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return self.first_name + " " + self.last_name

class Company(models.Model):
    class Meta:
        verbose_name_plural = "Companies"

    _id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=50, blank=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to="pfpCompany", default="placeholderCompany.png")

    def __str__(self):
        return self.name

class Job(models.Model):
    _id = models.BigAutoField(primary_key=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    title = models.CharField(max_length=30, blank=False)
    preffered_skills = models.JSONField(default=dict)
    connections = models.ManyToManyField('Human', through="Connection", related_name = 'job_human')
    
    def __str__(self):
        return f'{self.title} - {self.company.name}'

class Connection(models.Model):
    company = models.ForeignKey(Job, on_delete=models.CASCADE, default='', related_name='company_to_job')
    human = models.ForeignKey(Human, on_delete=models.CASCADE, default='', related_name='human_to_job')
    did_human_accept = models.BooleanField(default=False)
    did_job_accept = models.BooleanField(default=False)

如您所见,我尝试为工作与人的交互创建多对多连接

经过几篇帖子搜索、谷歌、youtube 和其他一些搜索后,我找到了以下序列化器:

class HumanSerializer(ModelSerializer):
    class Meta:
        model = Human
        fields = '__all__'


class CompanySerializer(ModelSerializer):
    class Meta:
        model = Company
        fields = "__all__"


class ConnectionSerializer(ModelSerializer):
    class Meta:
        model = Connection
        fields = '__all__'
        
class JobSerializer(ModelSerializer):
    human = HumanSerializer(many=True, read_only=True)
    # connections = ConnectionSerializer(source = 'connection_set',many = True, read_only=True)

    class Meta:
        model = Job
        fields = "__all__"
        depth = 1

这相当简单 现在,当我尝试调用服务器时,我得到 JSON 输出:

[
  {
    "_id": 1,
    "title": "testJob",
    "preffered_skills": {
      "skills": "python"
    },
    "company": {
      "_id": 1,
      "name": "testcomp",
      "image": "/images/placeholderCompany.png",
      "user": 2
    },
    "connections": [
      {
        "_id": 1,
        "first_name": "test",
        "last_name": "user",
        "image": "/images/placeholderHuman.png",
        "skills": {},
        "is_active": true,
        "user": 1
      }
    ]
  }
]

在连接[]内,我得到的只是人类序列化的内容,没有添加诸如

did_human_accept
之类的数据

预期输出应该类似于:

"connections": [
    {
      (human serialized),
      (company serialized),
      "did_human_accept" : 0,
      "did_job_accept": 0,
    }
]
python django-models django-rest-framework django-serializer
1个回答
0
投票

找到答案了! “联系”中的关系是从工作直接到人的 如果我想要一个完全序列化的连接,我需要调用 forgeinKey related_name

company_to_job = ConnectionSerializer(many=True, read_only=True)

class JobSerializer(ModelSerializer):
    human = HumanSerializer(many=False, read_only=True)
    company_to_job = ConnectionSerializer(many=True, read_only=True)

    class Meta:
        model = Job
        fields = "__all__"
        depth = 1
© www.soinside.com 2019 - 2024. All rights reserved.