在Django中,模型是一个Python类,它是Django模型的核心部分。以下是一些Django模型的常见用法和示例代码:
- 定义模型:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
- 添加字段选项:
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birth_date = models.DateField(blank=True, null=True)
- 创建多对多关系:
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, related_name='groups')
- 使用ForeignKey创建一对多关系:
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='groups')
- 使用OneToOneField创建一对一关系:
class Person(models.Model):
name = models.CharField(max_length=128)
class Profile(models.Model):
user = models.OneToOneField(Person, on_delete=models.CASCADE)
- 自定义模型管理器:
class PersonManager(models.Manager):
def get_adults(self):
return self.filter(age__gt=18)
class Person(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
objects = PersonManager()
- 使用Meta选项自定义表名和字段:
class Person(models.Model):
name = models.CharField(max_length=128)
class Meta:
db_table = 'custom_person_table'
- 创建一个抽象基模型:
class CommonInfo(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Person(CommonInfo):
name = models.CharField(max_length=128)
这些是Django模型的一些常见用法和示例。在实际应用中,你可以根据需要定义更复杂的模型关系和字段。