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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e9ff73b1-bf2f-462a-98f3-da46793c54da%40googlegroups.com.

Reply via email to