📜  polls models.py (1)

📅  最后修改于: 2023-12-03 15:33:43.834000             🧑  作者: Mango

Polls Models

The polls app in a Django project is responsible for creating and managing polls. It contains two models: Question and Choice.

Question model

The Question model represents a question in a poll. It has the following fields:

  • question_text: a string representing the question text.
  • pub_date: a DateTimeField representing the date and time the question was published.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
Choice model

The Choice model represents a choice in a poll. It has the following fields:

  • question: a ForeignKey to the Question model, representing the question the choice belongs to.
  • choice_text: a string representing the choice text.
  • votes: an IntegerField representing the number of votes the choice has received.
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

By default, Django creates a primary key field for every model called id. This field is not explicitly defined in the models above, but is automatically created by the framework.

The ForeignKey field is used to establish a one-to-many relationship between the Question and Choice models. This means that each Question can have multiple Choice objects associated with it, but each Choice object can only belong to one Question.

Both models inherit from Django's models.Model class.

Conclusion

The polls app models are designed to handle the creation and management of polls. They provide a simple and flexible way to store questions and choices related to a poll.