Lelouch
Lelouch

Reputation: 2193

Django + MySQL: performance on storing multiple foreign key

I have two models Post and Item that hope to have their images field, which refer to instances of a model Image:

class Image(models.Model):
    image = models.ImageField(upload_to='images')

The first approach I can think of is to add a TextField to both Post and Item, and store the image_instance.image.urls of Image instances, so each time I want to display all images of an item or post, I obtain the item.images and split the string into an array, and all the urls are there.

The second approach is to add post and item field to the Image model as nullable foreign key field. So each time I want to display all images of a post or item, I do something like Image.objects.filter(item=some_item_instance), and extract .image.url.

I wonder which approach is better in practice, Or there are other better approaches?

Upvotes: 0

Views: 99

Answers (1)

user764357
user764357

Reputation:

Just use a ManyToManyField to store the relationship between a Post (or Item) and an Image and then iterate across that. Have models.py like so:

class Image(models.Model):
    image = models.ImageField(upload_to='images')

class Post(models.Model):
    body = models.TextField()
    images = models.ManyToManyField(Image)

And elsewhere, pull the set of images from a Post instance and iterate across that:

my_post = Post.objects.first()
for image in my_post.images:
    print image.url

Upvotes: 1

Related Questions