Jorge Arévalo
Jorge Arévalo

Reputation: 3008

Django: Use other model classes as choices for a field

I'm writing a Django app that includes a poll section, and I want to offer the ability to create different types of questions. So, I have these models for the rating part

# Do I really need this class?
class BaseRating(models.Model):
    class Meta:
        abstract = True

# For questions like: "Rate your experience with XXXXX"
class FiveStarRating(BaseRating):
    rating = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MaxValueValidator(5)])

# For questions like: "Would you recommend XXXXX"?
class YesNoRating(BaseRating):
    rating = models.BooleanField()

I now want to create a new question, and I want to specify the rating system for it:

So, how should I design the question model?

class Question(models.Model):
    title = models.CharField(max_length=255)

    # rating??
    # I can't create a foreignkey field to the base class...

EDIT: I am finally using django-dynamic-forms, but I consider the first response as an acceptable one too

Upvotes: 0

Views: 898

Answers (1)

danidee
danidee

Reputation: 9634

From what i can see, you're not using the BaseRating model for anything, so it's safe to remove it.

As for the questions, in my case, i'll create two new models that have foreign keys to both FiveStarRating and YesNoRating so the data can be exclusive from each other. so you'll end up having two models like this.

class FiveStarQuestion(models.Model):
    title = models.CharField(max_length=255)
    rating = fields.ForeignKey(FiveStarRating)

class YesNoQuestion(models.Model):
    title = models.CharField(max_length=255)
    rating = fields.ForeignKey(YesNoRating)

but if you want to share the titles among the two questions (I would second this approach because there might be two questions with the same title)

Example: How would you rate Stackoverflow

and

How Satisfied are you with Stackoverflow

It makes sense to have only one title called Stackoverflow and use that Reference as a foreignkey in our tables. So in this case, you can keep the Question model and have ForiegnKey fields that point to it.

class Question(models.Model):
    title = models.CharField(max_length=255)

The create the two models as follows:

class FiveStarQuestion(models.Model):
    title = models.ForeignKey(Question)
    rating = fields.ForeignKey(FiveStarRating)

class YesNoQuestion(models.Model):
    title = models.ForeignKey(Question)
    rating = fields.ForeignKey(YesNoRating)

Upvotes: 1

Related Questions