Search code examples
pythondjangomodels

Django: Get selected fields from a One2Many relationship


In Django I have 2 tables in my models: app_title and the auth_user table. How do I query all rows while returning only the name field from app_title and the username and email fields from the auth_user table? It's basically a One2Many relationship. I can't seem to get it right.

class Title(models.Model):
    name = models.CharField(max_length=50)
    country = models.CharField(max_length=2)   # Don't return this field
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Solution

  • Do you need just
    titles = Title.objects.all().values('name', 'user__username', 'user__email')?
    - that give you a queryset with only those fields.
    More about values().