python - 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)
解决方案
因此,从我在这里看到的情况来看,如果您想要以下内容似乎很好:
- 用户只能拥有一个配置文件,并且一个配置文件仅与一个用户相关。
- 一个配置文件可以进行多个评论,但一个评论只属于一个配置文件。
- 一个产品可以有多个评论,但一个评论特定于一个产品。
根据删除后要保留在数据库中的内容,小心为外键定义 on_delete 参数。
来自文档的更多信息:https ://docs.djangoproject.com/fr/2.2/ref/models/fields/#arguments
推荐阅读
- c# - 一次调用从 Redis 读取多个哈希
- python - 检测 rasa_nlu 中的同义词
- python - openCL cv2.UMat 对象不可迭代
- excel - 所有日期变量的 IF 逻辑为空
- c++ - 从 Linux OMI (omicli) 到 Windows WMI 的连接失败并出现 DMTF 相关错误
- javascript - 解析嵌套的 javascript 对象
- serial-port - RS232 上的 DTR/RTS 可以用作 GPIO 来打开/关闭传感器吗?协议是否允许这种配置?
- logging - 在 IDE 中运行时的 Logback 配置
- git - 忽略已经提交给 git 的文件
- spring - 项目构建错误:io.zipkin.java:zipkin-autoconfigure-ui:jar 的“dependencies.dependency.version”缺失