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):
    fields....

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: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey

If you wish to integrate this into the Django Admin: https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.TabularInline

Docs for django-rest-framework and related serializers: https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Back to Top