简体   繁体   中英

django queryset of two models

I have two models:

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'),)

I need to make something like SQL JOIN between them and store joined table in queryset.

I tried to do this:

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)

But I had exception Encountered duplicate field name: 'id', which I don't know how to handle.

应该将named = True属性添加到namedtuple调用

namedtuple('Result', [col[0] for col in desc], rename=True)

You should use select_related and prefetch_related for these purposes.
When you want get table from related model, use 'select_related':

SocialAuthUsersocialauth.objects.select_related('user')  

When you want get all related tables, use 'prefetch_related':

AuthUser.objects.prefetch_relatd('socialauthusersocialauth_set')  

It will add to your querysets additional atribute, with name of related field. Also better add atribute related_name in ForeignKey for more explicit usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM