Access related table columns through ORM DJANGO

Asked

Viewed 763 times

2

How to access the object user and its attributes after a join?

This is my consultation

Idea.objects.select_related("user").values("author_id").annotate(
        qtd=Count('author_id'))

Example of a result:

<QuerySet [{'author_id': 1, 'qtd': 6}, {'author_id': 2, 'qtd': 8}]>

With this result, I can access the values author_id and qtd in my template:

 {% for d in ideas %}
    {{d.qtd}} - {{d.author_id}}
 {% endfor %}

However, I would need access to all columns of my table user so that I can access the fields of the Django admin system: username, email etc...

My model:

class UserProfile(models.Model):
    user = models.OneToOneField('auth.User', on_delete=models.PROTECT)
    use_term_accept = models.NullBooleanField(default=False)
    manager = models.NullBooleanField(default=False)

    def __str__(self):
        return self.user.username

class Idea(models.Model):
    title = models.CharField(max_length=200)
    creation_date = models.DateTimeField('data criação')
    author = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, related_name='old_author')
    authors = models.ManyToManyField('users.UserProfile', related_name='authors')
    deleted = models.BooleanField(default=False)

I hope I’ve been clear, when you doubt I’ll answer.

Obg

  • Hi mr.Abdo, I don’t understand well, the user table you cite is the one generated by the Userprofile class? Neither of the two models has the username and email values. Or you want to access the data of registered users by Django’s own administration system?

  • @Giovanemachado I want to access the data of the Django administration system. I edited the question to make it clear.

  • @Giovanemachado, forgot to answer another question. User is generated by Userprofile.

  • Right. I am checking the documentation, and I strongly believe that you can yes return the email and username of who is currently logged in. Probably just use: variable = User.objects.get(username). And for the same email, then I will elaborate better.

  • The problem is that I need to return the email inside the queryset so I can insert it into the template.

2 answers

1

1

Samyr, Have you ever tried to access the object? Despite that view that Django gives you from queryset your entire object will be there:

>>> p = Product.objects.select_related('category').last()
>>> p.category
>>> <Category: teste>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.