我有一个用户模型:
Class User(models.Model):
#some fields
另一个配置文件模型,由字段组成 - >母亲和父亲。
Class Profile(models.Model):
father = models.ForeignKey(
'User',
related_name='children',
on_delete = models.CASCADE)
mother = models.ForeignKey(
'User',
related_name='children',
on_delete = models.CASCADE)
现在,这样做是对的吗?如果是,我怎么才能得到用户的孩子?
答案 0 :(得分:2)
使用房产怎么样?
class User(models.Model):
#some fields
@property
def children(self):
if self.gender == 'm':
return self.father_children.all()
return self.mother_children.all()
和
class Profile(models.Model):
father = models.ForeignKey(
'User',
related_name='father_children',
on_delete = models.CASCADE)
mother = models.ForeignKey(
'User',
related_name='mother_children',
on_delete = models.CASCADE)
不理想,但这是
答案 1 :(得分:1)
将模型更改为
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# ....
gender = models.ChoiceField(choices=(('m', 'Male'), ('f', 'Female')))
# ....
def children(self):
if self.gender == 'm':
return self.fchildren
return self.mchildren
class Profile(models.Model):
father = models.ForeignKey(
'User',
related_name='fchildren',
on_delete = models.CASCADE)
mother = models.ForeignKey(
'User',
related_name='mchildren',
on_delete = models.CASCADE)
访问网址
user = User.objecets.get(pk=10)
children = user.children.all()