我有一个模特:
from django.contrib.auth.models import User
# Create your models here.
class Strategy(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mod_date = models.DateTimeField(auto_now=True)
strategy_name = models.CharField(max_length=20)
strategy = models.TextField()
position = models.TextField()
我想获得用户名=“leo”。
但在策略中,用户正在使用user_id。
如何使用username =“leo”获取“models.Strategy.objects.get”或“models.Strategy.objects.filter”?
谢谢。
答案 0 :(得分:3)
重复的问题Django models filter by foreignkey
Strategy.objects.filter(user__username='leo').first()
或
try:
Strategy.objects.get(user__username='leo')
except Strategy.DoesNotExists():
print 'username Leo does not exists'