Apostolos
Apostolos

Reputation: 8101

Present different models grouped using 2 common fields

My projects uses three Images models. The models are

STAGE = [
    ('Initial', 'Initial'),
    ('Observation','Observation'),
    ('Initial', 'Initial')
    ('Progress','Progress'),
    ('Final', 'Final'),
    ('Post treatment','Post treatment'),
]

class Xray(models.Model):
    date = models.DateTime()
    desc = models.CharField(choices=XRAY, max_length=15)
    stage = models.CharField(choices=STAGE, max_length=20)
    image = models.ImageField(...)


class External(models.Model):
    date = models.DateTime()
    desc = models.CharField(choices=EXTERNAL, max_length=15)
    stage = models.CharField(choices=STAGE, max_length=20)
    image = models.ImageField(...)

class Internal(models.Model):
    date = models.DateTime()
    desc = models.CharField(choices=INTERNAL, max_length=15)
    stage = models.CharField(choices=STAGE, max_length=20)
    image = models.ImageField(...)

I want to be able to display these three models on my template like so:

Date:Stage
    All pictures that have date = Date and stage=Stage

How can I group them so I am able to to this? Do you think It would be better if stage was a model by itself and be a foreignkey in every image mode and the date be a field of the stage model?

class Internal(models.Model):        
    desc = models.CharField(choices=INTERNAL, max_length=15)
    stage = models.CharField(choices=STAGE, max_length=20)
    image = models.ImageField(...)
    stage = models.ForeignKey(Stage)

class Stage(models.Model):
    title = models.CharField(choices=STAGE, max_lenght=20) 
    date = models.DateTime()

Notice that one picture can only have one date and be at one stage (so maybe better a OneToOne Field?)

Upvotes: 0

Views: 40

Answers (1)

arocks
arocks

Reputation: 2882

You can model Image as a Concrete Base Class

class Image(models.Model):
    date = models.DateTime()
    stage = models.CharField(choices=STAGE, max_length=20)
    image = models.ImageField(...)


class Xray(Image):
    desc = models.CharField(choices=XRAY, max_length=15)


....

Then you can query all three kinds of Image objects using normal syntax like:

Image.objects.filter(date=datetime.date(2014, 1, 3), stage='Initial') 

Upvotes: 1

Related Questions