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

How to access model from Foreign Key, Django?

I have 2 models in my project. What I want to do is access CustomUser model field "user_coins". But the problem is that I need to get it with only having offer_id from the TradeOffer model. So essentially what I would like to happen is to find the TradeOffer field with offer_id and through ForeignKey get the CustomUser field user_coins that the offer_id belongs to. I can’t seem to figure out how to do that.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)
    name = models.CharField(max_length=200, unique=True)
    user_coins = models.FloatField(default=0.00)
class TradeOffers(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    offer_id = models.CharField(max_length=150, unique=True)
    offer_state = models.IntegerField()
    offer_message = models.TextField(null=True)
    trade_id = models.CharField(max_length=150, unique=True, null=True)
    date_added = models.DateTimeField(auto_now_add=True)

>Solution :

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

Simple. To get the "user_coins" through "TradeOffers" objects you have to do this:

tradeoffer = TradeOffers.objects.get(offer_id = <whatever>) #Get the object.
user_coins = tradeoffer.name.user_coins #Get the user_coins field.

Or directly:

user_coins = TradeOffers.objects.get(offer_id = <whatever>).name.user_coins
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