Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting values from queryset in Django

Facing troubles with getting values from foreign key models.
I have one model, where included all foreign key relations.

class UserAccount(models.Model):
    name= models.CharField(max_length=100)
    surname = models.CharField(max_length=100)
    category= models.ManyToManyField(Category)
    account = models.ForeignKey(Account)
    country = models.ForeignKey(Country)
    permissions = models.ForeignKey(Permissions)


class Country(models.Model):
    iso_code = models.CharField(max_length=6)
    zip_code = models.CharField(max_length=10)

I’m using this to get all fields related to model UserAccount:

user_account_data = UserAccount.objects.all()
name = user_account_data.values_list('name', flat=True)))
surname = user_account_data.values_list('surname', flat=True)))

But when trying this, its giving me: ‘QuerySet’ object has no attribute ‘country’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

countries = user_account_data.country.values('iso_code')

>Solution :

try this

countries = user_account_data.values('country__iso_code')

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.values

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading