Gie
Gie

Reputation: 1939

Get object from model based on ForeignKey object

I have some problem with getting object from my model. I've something like this:

 # Model
 class Subscription(models.Model):
    identifier = models.CharField(max_length=10)
    user = models.ForeignKey(User)

 class Subscriber(models.Model):
    name = models.CharField(max_length=5)

And now I have Subscriber object instance my_user, and I want to get related subscription. So I'm trying something like:

 sub = Subscription.objects.get(user=my_user)

but I'm getting exception after that. I also' tried:

 sub = Subscription.objects.get(user.id=my_user.id)

Result still is the same (exception).

Do you have any suggestions or link to documentation, how can I get this object from Subscription collection?

Upvotes: 2

Views: 523

Answers (1)

James R
James R

Reputation: 4656

At least based on the models you provided above, I'm not sure why there should be a relation at all.

Subscriber is not related in anyway to Subscription and specifically, the primary IDs of model probably shouldn't be related (user.id=my_user.id), unless you are designing it explicitly like that.

Moreover, this:

sub = Subscription.objects.get(user=my_user)

will only work if there if there is some sort of relation that django knows about.

In my view you should do something like this:

 class Subscription(models.Model):
    subscriber= models.ForeignKey('Subscriber')
    identifier = models.CharField(max_length=10)


 class Subscriber(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=5) #PS, if you ever save anything longer than 5 char's this will raise an exception.

This will allow you to make queries like:

my_user = Subscriber.obejects.get(something=someotherthing)
sub = Subscription.objects.get(subscriber=my_user)

Upvotes: 3

Related Questions