Django: Use other model classes as choices for a field - python

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:
If I create the question "How would you rate xxxxx", I'd use FiveStarRating model
If I create the question "Are you satisfied with xxxx", I'd use YesNoRating
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

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)

Related

Django Problem : I want to see reverse order in django admin many to many field

This is my model.py code
class Question(models.Model):
id = models.AutoField
question = models.CharField(max_length=100)
answer = models.CharField(max_length=100)
class TestSeries(models.Model):
id = models.AutoField
quiz_name = models.CharField(max_length=100)
all_question=models.ManyToManyField(MyQuestion)
When i open my admin panel on test series
previous added are shown in order : Oldest first
I want to see that in newest first manner.
There are two things OP needs to do
Store in the models when the object was created / updated.
Order based on the creation date. To do so, one can add to the model a Meta option named ordering or define a custom form to be used in the Django Admin. Example 1, Example 2.

Correctly defining this data relation in Django models

I'm working on a Django project, where I have amongst others, two models that have a relationship.
The first model describes a dish in general. It has a name and some other basic information, for instance:
dish(models.Model):
name = models.CharField(max_length=100)
short_desc = models.CharField(max_lenght=255)
vegetarian = models.BooleanField(default=False)
vegan = models.BooleanField(default=False)
The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So the dish gets a new field, which points to the current preparation text.
preparation = models.???(???)
So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.
The preparation itself looks like this:
preparation(models.Model):
prep_test = models.TextField()
ingredients = models.TextField()
last_update = models.DateTimeField()
As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.
Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?
If you have multiple preparations for the dish, you don't have a one-to-one relationship by definition.
The way to define this is a ForeignKey from Preparation to Dish. (Note, Python style is that classes start with an upper case letter.)
class Preparation(models.Model):
...
dish = models.ForeignKey('Dish')
Now you can do my_dish.preparation_set.latest('last_update') to get the latest preparation for a dish. If you add an inner Meta class to Preparation and define get_latest_by = 'last_update'), you can leave out the parameter to the latest() call.
Make sure, relations are correct otherwise you have repeating tuples in your models which is not very good practice, make your database very heavy. see relation from my perspective.
class dish(models.Model):
name = models.CharField(max_length=100)
short_desc = models.CharField(max_lenght=255)
vegetarian = models.BooleanField(default=False)
vegan = models.BooleanField(default=False)
class Ingredients(models.Model):
name = models.CharField(max_length=100)
dish = models.ForeignKey(dish)
class preparation(models.Model):
prep_test = models.TextField()
last_update = models.DateTimeField()
dish = models.OneToOneField(dish)
why you don't make one2many relation of dish with preparation.
I dish have multiple preparation but have only one active. you can attach latest on base of last_update = models.DateTimeField()
your model will be like:
class preparation(models.Model):
dish = models.ForeignKey(dish)
...

Model redundant django tables?

I am working to figure out the model for a Django project: an app to track Books.
Among other fields, every Book has either/both a Printer and a Publisher, which are basically identical. So, here's how it stands:
class Book(models.Model):
title = models.CharField(max_length=100)
printer = models.ForeignKey('Printer')
publisher = models.ForeignKey('Publisher')
class Printer(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
class Publisher(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
It seems to me this is bad database form: it's not DRY. In addition, quite often, a Book might be printed by a firm which publishes the same or another book: in other words, the tables can overlap. So, the two models Printer and Publisher should really be combined, while they need to remain distinct in the admin.
My question: how best to do this? Should I create another model, Firm, and create one-to-one relationships between it and Printer/Publisher?
The Django way to handle that is to create an Abstract Base Model. This is the DRY way to create your models. Here is the code:
class BaseModel(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
class Meta:
abstract = True
class Printer(BaseModel):
pass
class Publisher(BaseModel):
pass
This will allow you to specify redundant fields only once. Also, if you need to add any extra fields to one model, just add them instead of using pass.

How do I make a class a sub-group of another class?

from django.db import models
class products(models.Model): #Table name, has to wrap models.Model to get the functionality of Django.
name = models.CharField(max_length=200, unique=True) #Like a VARCHAR field
description = models.TextField() #Like a TEXT field
price = models.IntegerField()
def __unicode__(self): #Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
return self.name
class categories(models.Model):
I'm a python newbie and I'm trying to create an e-commerce store. As you can see above, I've created the products class, but in the Categories class, I need to include all the products I create come under a certain category. I have no clue how to do this.
Sounds like you just want a ForeignKey from Product to Category.
Take a look at Many to Many
I think a Product can belong to Many categories so it should have a ManyToMany relationship to the Category model.

Django: Referencing a manytomany field that has been defined in another model

I'm trying to work out how to calculate the number of books written by an author. The book model sets up the manytomany field with the author model. I have no idea how even google something like this which I thought would be very simple to do but I don't even know how to start.
Here's the stripped down code:
class Author(models.Model):
first_name = models.CharField()
last_name = models.CharField()
def books(self):
"""Return a list of comma separated list of books by the author"""
pass
class Book(models.Model):
title = models.CharField()
authors = models.ManyToManyField(Author)
Maybe I could do a filter query to get books by a particular author but it doesn't seem like the django way to do it? I'm also not sure how to pass the filter function a python object rather than text.
Thanks
when you define a foreignkey or manytomany field, django sets up a reverse relation for you, which in your case is book_set. so something like:
def books(self):
books = self.book_set.all()
return ', '.join([book.title for book in books])
see related objects in the docs

Categories

Resources