Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models ForeignKey return IDs

I have been trying to search forums to get an answer for this, but it seems like its a bit tricky to search.

I have the following model which is pulling users from django User table:

class trendingidea(models.Model):
        iname = models.CharField(unique=True, max_length=15)
        idea = models.TextField(unique=True)
        submittedon = models.DateTimeField()
        support = models.PositiveSmallIntegerField()
        readbyadmin = models.BooleanField()
        feasibilitycheck = models.BooleanField()
        submittedby = models.ForeignKey(User,related_name="submitted_by")
        assignedto = models.ForeignKey(User, blank=True, null=True, related_name="assignedto")

However when i query the database and pull the information:

ti=list(trendingidea.objects.values())

print(ti)

[{'readbyadmin': False, 'id': 1, 'idea': 'cisco', 'feasibilitycheck': True, 'submittedby_id': 1, 'support': 1, 'submittedon': datetime.datetime(2017, 11, 6, 11, 8, 10, tzinfo=<UTC>), 'iname': 'cisoc', 'assignedto_id': 1}]

in place of submittedby and assignedto it gives me submittedby_id: 1 and assignedto_id: 1.

I wanted the usernames and not their IDs. is there a way to achieve this?

like image 258
Adarsh Chauhan Avatar asked Mar 28 '26 22:03

Adarsh Chauhan


1 Answers

You can, by referring to the related field with the __ prefix. The only downside is that you have to list all the other fields as well:

trendingidea.objects.values('readbyadmin',
                            'id',
                            'idea',
                            'submittedon',
                            'support',
                            'readbyadmin',
                            'feasibilitycheck',
                            'submittedby__name',
                            'assignedto__name')

Note that your dictionary will have submittedby__name and assignedto__name keys.

like image 196
Burhan Khalid Avatar answered Apr 01 '26 06:04

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!