Django 中另一个模型中对同一模型的多次引用
您好,我的系统中有很多用户,他们被分为不同的类型。我想存储所有这些用户的地址详细信息。例如,用户可以是学生、学校或特许经营商。这里的所有用户都可以拥有与其相关联的地址信息。
from django.db import models
from django.contrib.auth.Models import User
class Address(models.Model):
user = models.OneToOneField(User)
address = models.TextField()
class Student(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
class School(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
contact_person_name = models.CharField(max_length=50)
在这种情况下,有 2 个对 User 模型的引用 - 一个通过 user_id,另一个通过 address.user,尽管它们应该引用同一个实例。重复引用是一种不好的做法吗?
我想过在地址中省略“用户”外键,但我认为没有用户该地址就不可能存在。如何更好地建模?
Hi I have a lot of users in my system who are classified into different types. I want to store the address details of all those users. For instance the user could be a student, a school or a franchisee. All the users here could have an address information associated with them.
from django.db import models
from django.contrib.auth.Models import User
class Address(models.Model):
user = models.OneToOneField(User)
address = models.TextField()
class Student(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
class School(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
contact_person_name = models.CharField(max_length=50)
In this scenario there are 2 references to the User model - one through user_id and another through address.user though they should be referring to the same instance. Is it a bad practice to have duplicate references?
I thought of leaving out the 'user' foreignkey in Address, but I think that the address can't exist without a user. How to better model this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您在问题中已经提到的相同字段的重复
模型不是一个好主意。
如果这些是您的实际模型,我建议您使用 抽象的
models:
这将生成两个表:students、schools 以及字段
用户、地址和用户、地址、contact_person_name
分别。
As you already mentioned in question duplication of same field in
a model is not a good Idea.
If these are your actual models, I would suggest you using abstract
models:
This will generate two tables: students, schools with fields
user, address and user, address, contact_person_name
respectively.