我有两种模式:
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
username = models.CharField(unique=True, max_length=30)
class Meta:
managed = False
db_table = 'auth_user'
class SocialAuthUsersocialauth(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
provider = models.CharField(max_length=32)
uid = models.CharField(max_length=255)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
extra_data = models.TextField()
class Meta:
managed = False
db_table = 'social_auth_usersocialauth'
unique_together = (('provider', 'uid'),)
我需要在它们之间创建类似SQL JOIN的东西,并在queryset中存储连接表。
我试着这样做:
def namedtuplefetchall(cursor):
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
def examp(request):
context = dict()
cursor = connection.cursor()
cursor.execute("""
SELECT *
FROM auth_user
JOIN social_auth_usersocialauth
ON auth_user.id = social_auth_usersocialauth.user_id
""")
context['usersauth'] = namedtuplefetchall(cursor)
return render(request, 'try.html', context)
但我有例外遇到重复的字段名称:' id',我不知道如何处理。
答案 0 :(得分:1)
应将rename = True属性添加到namedtuple调用
namedtuple('Result', [col[0] for col in desc], rename=True)
答案 1 :(得分:0)
出于这些目的,您应该使用select_related
和prefetch_related
如果您想从相关模型中获取表格,请使用“select_related':
SocialAuthUsersocialauth.objects.select_related('user')
如果要获取所有相关表格,请使用' prefetch_related':
AuthUser.objects.prefetch_relatd('socialauthusersocialauth_set')
它将向您的查询集添加其他属性,其名称为相关字段。还可以在related_name
中更好地添加属性ForeignKey
,以便更明确地使用。