首页 > 解决方案 > Django - 模型中的关系

问题描述

在 Django 中有称为 ForeignKey 和 OneToMany/OneToOne 的字段类型,我想知道在这种情况下我会使用 ForeignKey 还是关系类型作为字段类型?User to Profile 已被确定为 OneToOne,但我不确定其他人。

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    fullname = models.CharField(max_length=100)
    dob = models.DateField()
    address = models.TextField()
    city = models.CharField(max_length=100)
    profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images')

class Product(models.Model):
    name = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    category = models.CharField(max_length=100)
    releasedate = models.DateField()
    description = models.TextField()
    productphoto = models.ImageField(default='default_product.jpg', upload_to='reviewApp/static/product_images')

class Review(models.Model):
    product = models.ForeignKey(Product)
    profile = models.ForeignKey(Profile)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = model.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)])
    reviewtext = models.TextField()
    postdate = models.DateTimeField(auto_now_add=True)
    lastmodified = models.DateTimeField(auto_now=True)

项目的 ERD

标签: pythondjangodjango-models

解决方案


因此,从我在这里看到的情况来看,如果您想要以下内容似乎很好:

  • 用户只能拥有一个配置文件,并且一个配置文件仅与一个用户相关。
  • 一个配置文件可以进行多个评论,但一个评论只属于一个配置文件。
  • 一个产品可以有多个评论,但一个评论特定于一个产品。

根据删除后要保留在数据库中的内容,小心为外键定义 on_delete 参数。

来自文档的更多信息:https ://docs.djangoproject.com/fr/2.2/ref/models/fields/#arguments


推荐阅读