Home > Enterprise >  Django get queryset with column from another model
Django get queryset with column from another model

Time:10-17

Hello this is my model related to default AUTH_USER_MODEL by OneToOneField:

class Additional(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE)
    vut_id = models.IntegerField()
    edit_right = models.BooleanField(default = False)
    add_access_right = models.BooleanField(default = False)

and I need to get Queryset of data Additional model with username from model AUTH_USER_MODEL.

If used select_related (Additional.objects.select_related('user').all() ) it returned only id of user:

{
    "model": "authentication.additional",
    "pk": 13,
    "fields": {
        "user": 15,
        "vut_id": 123456,
        "edit_right": false,
        "add_access_right": false
    }
}

how i want it to looks like:

{
    "model": "authentication.additional",
    "pk": 13,
    "fields": {
        "username": "user1",
        "vut_id": 123456,
        "edit_right": false,
        "add_access_right": false
    }
}

CodePudding user response:

Additional.objects.select_related("user").all().values("user_id","user__username", "user__first_name","user__last_name", ...other fields whichever you want)
  • Related