Tuesday, December 31, 2019

Re: link multiple files to model

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:
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



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b68b340c-f96b-4d40-ba35-c6e191c278ab%40googlegroups.com.

No comments:

Post a Comment