1

I have a model:

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()

I want to get username = "leo".

But in Strategy's user is using user_id.

How to get "models.Strategy.objects.get" or "models.Strategy.objects.filter" using username = "leo"?

Thank you.

yensheng
  • 1,315
  • 2
  • 14
  • 22

1 Answers1

3

Duplicated question Django models filter by foreignkey

Strategy.objects.filter(user__username='leo').first()

or

try:
    Strategy.objects.get(user__username='leo')
except Strategy.DoesNotExists():
    print 'username Leo does not exists' 

Documentation

Community
  • 1
  • 1
alfredo138923
  • 1,509
  • 1
  • 15
  • 15