On Nov 25, 12:42 pm, Clemens Wältken <clem...@waeltken.de> wrote:
> Hey everyone!
> Iam new to this mailinglist and django + python in general.
> Yesterday I came up with a pretty complex question concerning abstract
> classes and relations.
> I have modeled the following classes:
>
>      Question
> /Answer
> /YesNoAnswer
>          FreeAnswer
>
> Answer should be abstract (note the italic text;) and has a one-to-one
> relation to question.
> In django both directions of this relation are navigable (by default)
> and this is intended, BUT by adding more concrete classes of Answer i
> automaticly create new fields in Question, like yesnoanswer and
> freeanswer and maybe many more. This kindof breaks the one-to-one
> relationship. In an ideal world id like to access the concrete Answer by
> calling Question.answer, i therefore wrote the kinda handy method
> getAnswer() to emulate this behavior. Is there a more elegant way to do
> this? Did i miss something in the django documentation? (Note that
> setting the related_name wont do the trick)

I am afraid that there is no easier way to do this. If I understand
the code correctly, what is happening is that each question can have
multiple answers, but a single one of any given type. So, there is
nothing in Django (or in the DB) restricting each question to have
just one answer. If you keep this data model, then it would be good to
add a db check or at least check on question.save() so that each
question can have just a single answer defined.

This could be modeled also in one of the following ways:
 - There is just one Answer model, with two fields: value and type.
Value could be free text, for YesNoAnswer 'yes' or 'no', and type
would be 'yesnoanswer'. This is problematic, since if you want to have
for example DateAnswer, then for efficient lookups (for example
answer__lte=datetime.date.today()), you would need to write custom SQL
so that you can cast the value to proper type.
 - The other possible way is to have one single big answer class with
a field for each type of possible answer. The type of the answer is
defined by which field is not null. This is the way I would model
this, as there is just one field with non-null answer, the extra null
fields consume next to nothing (just one bit per field) in the DB.

Also, why do you need to separate the answer model from the question?
Wouldn't it be best to have the answer directly in the question?

 - Anssi Kääriäinen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to