如何使用ForeignKey关系显示许多字段的值?

时间:2019-09-25 11:29:30

标签: django django-rest-framework

在寻找此问题的解决方案时,我遇到了一些类似的线程,但是指的是Django / DRF的旧版本,因此在我的情况下不起作用。

有以下两种模型:

class CsdModel(models.Model):
   model_id = models.CharField("Item ID", max_length=8, primary_key=True)
   name = models.CharField("Item Name", max_length=40)
   active = models.BooleanField(default=True)

   def __str__(self):
       return self.model_id


class CsdListing(models.Model):
   model_id = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_id')
   name = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_name')
   (...)

编辑:序列化器的定义方式如下:

class CsdModelSerializer(serializers.ModelSerializer):
   model_id = serializers.RegexField(regex='^\w{2}\d{3}$', allow_blank=False)
   name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)

   class Meta:
      model = CsdModel
      fields = '__all__'


class CsdListingSerializer(serializers.ModelSerializer):
   session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)

   def validate_session_id(self, value):
      (...)

   class Meta:
      model = CsdListing
      fields = '__all__'

我想看到的是model_id中的nameCsdModel在基于CsdListing模型创建的表单中显示。但是,该ID是重复的:

Form Capture

我应该如何重建模型以在表格中同时显示ID和名称?

1 个答案:

答案 0 :(得分:0)

您应该只有一个外键。但是,列表序列化程序应随后将模型引用为嵌套序列化程序。

class CsdListing(models.Model):
   model = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='listing')

class CsdListingSerializer(serializers.ModelSerializer):
   model = CsdModelSerializer()
   session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)