Access related table columns via ORAN DJANGO

2

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

This is my query

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 author_id and qtd values in my template:

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

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

My template:

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 to have been clear, any doubt I will answer.

Obg

    
asked by anonymous 22.11.2018 / 15:29

2 answers

1

I was able to solve this problem. I'll register here to help someone if they pass by.

I passed the key author__user__email to the result putting author__user__email into values.

Idea.objects.values("author_id", "author__user__email").annotate(
    total=Count('author_id'))

link

    
23.11.2018 / 10:31
1

Samyr, Have you tried to access the object? In spite of this visualization that Django gives you the queryset your entire object will be:

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