如何从其他表中使用联接Django Rest框架获取数据

时间:2019-11-14 08:09:33

标签: django django-models django-rest-framework

我有两个模型,第一个是

class Event(models.Model):
    main_image = models.ImageField(upload_to='events/images', default="")
    event_name = models.CharField(max_length=100, default="")
    event_organizer = models.ForeignKey(
    Organizer, on_delete=models.CASCADE, limit_choices_to={'is_active': True})

另外一个是

class additional_images(models.Model):
   # When a Event is deleted, upload models are also deleted
   event = models.ForeignKey(Event, on_delete=models.CASCADE)
   image = models.FileField(upload_to='events/images', null=True, blank=True, default="")

和序列化器类由

给出
class eventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = ['id', 'main_image', 'event_name', 'event_address', 'event_organizer']

我的问题是如何通过additional_images获得eventSerializer

3 个答案:

答案 0 :(得分:1)

感谢熊布朗。他的评论很有帮助,我将其发布为答案 更新我的additional_images模型

class additional_images(models.Model):

    event = models.ForeignKey(Event, on_delete=models.CASCADE, 
                             related_name="additional_images",
                             related_query_name="additional_image",)
   image = models.FileField(upload_to='events/images', null=True, blank=True, default="")

为此创建序列化器类

class additionalImagesSerializer(serializers.ModelSerializer):
    class Meta:
        model = additional_images
        fields = ['image']

eventSerializer类中

class eventSerializer(serializers.ModelSerializer):
    additional_images = additionalImagesSerializer(many=True, read_only=True)
    class Meta:
        model = Event
        fields = ['additional_images', 'id', 'main_image', 'event_name', 
                  'event_address',  'event_organizer']

那是完美的工作!

答案 1 :(得分:0)

您可以在文档中了解ForeignKey以及如何访问它们之间的关系。

但是,您可以执行以下操作:

1)(可选)指定related_name:

class additional_images(models.Model):
   # When a Event is deleted, upload models are also deleted
   event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="images")

2)您现在可以使用event.images访问它。因此,您可以在序列化程序中使用它:

class eventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = ['id', 'main_image', 'event_name', 'event_address', 'event_organizer', 'images']

现在,您将获得图像作为图像ID的列表。如果您有图片序列化程序,则可以在事件序列化程序中指定嵌套的序列化程序。

代码审查注释:您有3个类,每个类都有不同的命名约定。坚持一个,最好是-> EventSerializer

答案 2 :(得分:0)

class eventSerializer(serializers.ModelSerializer):
    image = serializers.CharField(source='additional_images.get_image_url', read_only=True)
    additional_images = serializers.PrimaryKeyRelatedField(queryset=additional_images.objects.all())
    class Meta:
    model = Event
    fields = ['id','main_image', 'event_address',  'event_organizer', 'additional_images', 'image']

并在模型中定义获取图片网址方法

class additional_images(models.Model):
   .........
   def get_image_url(self):
       returen "%s,%s" %(settings.MEDIA_URL, self.image)