简体   繁体   English

如何从外键访问model,Django?

[英]How to access model from Foreign Key, Django?

I have 2 models in my project.我的项目中有 2 个模型。 What I want to do is access CustomUser model field "user_coins".我想要做的是访问 CustomUser model 字段“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.但问题是我只需要从 TradeOffer model 中获得 offer_id。所以基本上我想要发生的是找到带有 offer_id 的 TradeOffer 字段,并通过 ForeignKey 获取 offer_id 所属的 CustomUser 字段 user_coins。 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:要通过“TradeOffers”对象获取“user_coins”,您必须这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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