How to separate the image model from the other models and create relation between it and others and create more than one image for a object

I want to make an image model and some other models that may have several photos for each object. How can I implement it in Django and Rest Framework?

I'll give you an example, it's pretty easy to figure out the rest. Please don't ask us to write your code.

class Image(models.Model):
    image = models.ImageField(...)
    mymodel = models.ForeignKey('myapp.MyModel',related_name="images",...)

class MyModel(models.Model):

And to get all the images you can do:

mymodel = MyModel.objects.get(pk=my_pk)
images = mymodel.images.all()

For serializing:

class ImageSerializer(serializers.ModelSerializer):
     class Meta:
        model = Images
        fields = '__all__'

class MyModelSerializer(serializers.ModelSerializer):
    image_list = ImageSerializer(Many=True)
    class Meta:
        model = MyModel
        fields = ['image_list', ...]

Please have a look at:

If you wish to integrate this into the Django Admin:

Docs for django-rest-framework and related serializers:

Back to Top