简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM