我需要在 ModelSerializer 上的已登录用户中获取 FK 信息以添加新模型。
在这种情况下,用户-> 业务和客户-> 业务。发布客户端时,我需要使用登录的用户业务设置业务 ID。
重要的是要说所有其他模型具有相同的行为。我正在为这个问题寻找一些通用的解决方案。
客户模型
class Client(SoftDeletionModel):
object = ClientManager
business = models.ForeignKey(Business, related_name='business_clients', on_delete=models.CASCADE)
company_name = models.CharField(max_length=511, verbose_name=_('Company Name'))
cnpj = models.CharField(max_length=14, verbose_name=_('CNPJ'))
用户模型
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(_('email address'), unique=True)
business = models.ForeignKey(Business, related_name='business', on_delete=models.CASCADE, null=True)
客户端序列化器
class ClientSerializer(serializers.ModelSerializer):
business = serializers.IntegerField() # here how can I get user.business?
deleted_at = serializers.HiddenField(default=None)
active = serializers.BooleanField(read_only=True)
password = serializers.CharField(write_only=True, required=False, allow_blank=True)
password_contract = Base64PDFFileField()
class Meta:
model = Client
fields = '__all__'
validators = [
UniqueTogetherValidator2(
queryset=Client.objects.all(),
fields=('cnpj', 'business'),
message=_("CNPJ already exists"),
key_field_name='cnpj'
),
UniqueTogetherValidator2(
queryset=Client.objects.all(),
fields=('email', 'business'),
message=_("Email already exists"),
key_field_name='email'
)
]