link multiple files to model

21 views
Skip to first unread message

Bart Jonkers

unread,
Dec 29, 2019, 4:26:35 PM12/29/19
to Django users
Hi,

I have a question about one-to-many relations in models
What is best to use? ForeignKey of many to ManyToManyField?
I want to attach files to a model. 

The ForeignKey is easy to use. 
class Feed(models.Model):
    user=models.ForeignKey(User, on_delete=models.CASCADE, related_name='feeds')
    text=models.TextField(blank=False, max_length=500)

class FeedFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")
    feed = models.ForeignKey(Feed, on_delete=models.CASCADE, related_name='files')

But retrieving all objects (for a listview) with all files included the object is challenging. I
 tried subqueries, prefetch_related...
How can I do this?
AllFeeds = Feed.objects.all() 

the manytomany-solution:
class Feed(models.Model):
    user=models.ForeignKey(User, on_delete=models.CASCADE, related_name='feeds')
    text=models.TextField(blank=False, max_length=500)
    files=models.ManyToManyField(FeedFile)

class FeedFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")
Is not so intuitive for the user, but I can get the correct queryset.

Any advise on good practise?

Bart



Bart Jonkers

unread,
Dec 31, 2019, 6:09:14 AM12/31/19
to Django users
My quick solution:

I'm using django-sql-utils to get SubqueryAggregate.
I annotate 2 array's: one for the filelink and one for the filedescription.
In a custom template tag I merge the two arrays and render download buttons.

It would be great to annotate lists from an other model, but need more time to figure this out.

Bart



Op zondag 29 december 2019 22:26:35 UTC+1 schreef Bart Jonkers:
Reply all
Reply to author
Forward
0 new messages