简体   繁体   中英

Collect separate models in Django

I have a model Content . This model's objects should be the only objects the user sees.

But the objects have to handle images, videos, article etc.

I think the best solution would be to have a model for each type of content:

class Image(models.Model):
    image = ImageField()

class Article(models.Model):
    title = CharField(max_length=100)
    text = TextField()

class Video(models.Model):
    url = URLField()

And the content will then be controlled with something like

class Content(models.Model):
    content = ForeignKey(to=?)

Actually a Content object can have more than 1 image, video, article etc. So I guess I will need to create another model ContentSet which may have either 1 or multiple images, videos or articles.

The advantages will be that I can categorize, have comments etc. in the Content object rather than handling this in all the models Image , Article , Video .

I need some advice on how to do this. Is it a good strategy? Will it probably be better to use GenericRelation ? What model should my ForeignKey point to in my Content model?

I hope my idea is clear to understand. I don't know any sites doing this, so I can't refer to anything to explain it better.

you could also model this relationship polymorphicaly

I started to use django-polymodels becasue it is very lightweight

https://github.com/charettes/django-polymodels

You could create a content superclass

class Content(PolymorphicModel):
  pass    

class Image(Content):
  pass

class Article(Content):
  pass

and then to get all subclasses of Content

Content.objects.all().select_subclasses()

The documentation link I have listed above pretty much uses your exact problem as a use case, it has better examples and all the caveats involved. I use it in production for a large website and it is extremely easy API and as long as the joins are understood performant.

Additionally, it is way cool because you can refer to content in FK and M2M relationships

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM