Reputation: 2445
I have a situation I don´t know how to model correctly. I want every child of a class to be associated with a media object (photo, video or music). I want to know which is the preffered approach to this problem. What I have right now is:
class Something(models.Model):
media = models.ForeignKey(Media)
class Media(models.Model):
title = models.CharField(max_lenght=100)
def get_tiny_object():
pass
def get_big_object():
pass
class Picture(Media):
picture = models.ImageField()
def get_tiny_object():
return ...
...
class Video(Media):
video = models.CharField(max_length=200) #youtube id
...
class Music(Media):
music = ....
You get the idea. ¿Does this work? Should I also record on "Something" what kind of media it is?
EDIT:
The idea behind having a Media class, is that I can render in the templates without knowing which kind of media I´m rendering. get_tiny_object() should return, if it is a picture:
"<img style="width:60px; height: 50px" ...>"
So if I have a foreign key to a media object lets say it's id=4, does django know that it should be fetched from music table, if the object I associated with is of Music kind? Because I´ll have 3 different id=4, one on each table (picture, video and music (and possibly more if the domain changes)).
Upvotes: 0
Views: 429
Reputation: 6620
I still think the question is a little hard to understand - the title is Database modelling in Django after all...However, this is a perfectly valid and reasonable thing to do, and seems to fit your intent:
The recommended way to do this is multi table inheritance - example:
class Media(models.Model):
pass
class Something(models.Model):
media = models.ForeignKey(Media)
class Picture(Media):
foo = models.CharField(max_length=100)
def get_tiny_object(self):
return self.foo
class Video(Media):
bar = models.CharField(max_length=100)
def get_tiny_object(self):
return self.bar
picture = Picture.objects.create(foo='some picture')
video = Video.objects.create(bar='some video')
something1 = Something.objects.create(media=picture)
something2 = Something.objects.create(media=video)
print something1.media.get_tiny_object() # this is a picture remember?
print something2.media.get_tiny_object() # and lo, here is a video
Upvotes: 2
Reputation: 2259
http://docs.djangoproject.com/en/dev/topics/db/models/#one-to-one-relationships
this says you should use a OneToOneField relating each Picture, Video, Music to a Media entry, and they all inherit directly from models.Model.
Also, you need to change your Something to
class Something(models.Model):
media = models.ForeignKey("Media")
because since Media isn't defined when you define Something (if you place it below it), it won't work, django provides you with the possibility of doing this with the classname instead of a reference to the class
Upvotes: 0