如何使用joindjango-Rest框架从其他表中获取数据



我有两个型号,第一个是

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']

我的问题是如何用eventSerializer得到additional_images

感谢Bear Brown。他的评论很有帮助,我把它作为回答发布更新我的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']

干得不错!

您可以在文档中了解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

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']

并在你的模型中定义一个获取图像url的方法

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

相关内容

  • 没有找到相关文章

最新更新