Python Django-对两个外键使用同一列
我有三种型号:Python Django-对两个外键使用同一列,python,django,foreign-keys,Python,Django,Foreign Keys,我有三种型号: class UserProfile: user_id = OneToOneField(User, related_name='profile') name = CharField class User: # standard django model class Channel: owner = ForeignKey(User) 现在,我想让频道过滤用户名。所以我能做的是: Channel.objects.filter(owner__profile_
class UserProfile:
user_id = OneToOneField(User, related_name='profile')
name = CharField
class User:
# standard django model
class Channel:
owner = ForeignKey(User)
现在,我想让频道过滤用户名。所以我能做的是:
Channel.objects.filter(owner__profile__name__icontains='foo')
但这将连接用户表,然后连接UserProfile,这不是最好的,因为我想在User_id上连接UserProfile表(我将使用一个连接而不是两个连接)
我尝试向模型添加另一个外键,如下所示:
class Channel:
owner = models.ForeignKey(
User,
db_column='owner_id',
)
owner_profile = models.ForeignKey(
UserProfile,
db_column='owner_id',
to_field='user_id')
但是Django不喜欢
posts.Post: (models.E007) Field 'owner_profile' has column name 'owner_id' that is used by another field.
HINT: Specify a 'db_column' for the field.
是否有任何干净的解决方法?要使其正常工作,您必须假设User和UserProfile表具有相同的ID值。没有理由是这样的。不,请注意第二个ForeignKeyGreat问题上的_字段,遇到了一种相同的问题-我有唯一的
uuid
值,在三个不同的表中提到-a、B、C,我想使用C的相同底层列,从C到a和B对象都有一个ORM引用。。。