Junior
What are the models available in Django?
sobes.tech AI
Answer from AI
In Django models — these are Python classes that represent the data structure in a database. Each model corresponds to a single table in the database.
Main types of model fields:
CharField: String (with length limit).TextField: Long text.IntegerField: Integer.FloatField: Floating point number.BooleanField: Boolean value (True/False).DateField: Date.DateTimeField: Date and time.EmailField: Field for email address.URLField: Field for URL.FileField: Field for uploading files.ImageField: Field for uploading images (inherits fromFileField).
Relationships between models:
ForeignKey: "One-to-many" relationship.# Each article belongs to one author class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100)ManyToManyField: "Many-to-many" relationship.# Each article can have multiple tags, and each tag can have multiple articles class Article(models.Model): tags = models.ManyToManyField(Tag) title = models.CharField(max_length=100)OneToOneField: "One-to-one" relationship.# Each user can have only one profile class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField()
Each model has necessary attributes and methods:
objects: The default manager used to perform database queries.__str__: Method that returns the string representation of the model object.class Article(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title # Displays the article title in admin and console
Models are defined in the models.py file of the app. After defining models, migrations (makemigrations, migrate) must be run to create the corresponding tables in the database.