0

I have two models:

class A(models.Model):
    # fields

class B(models.Model):
    a       = models.ForeignKey(A)
    name    = models.CharField(max_length=64)

What I want to do is to get a filtered queryset from A in addition to the related objects from B and append them to the queryset from A, so I would be able to access name field this way: A.B.name

Any idea how to do this?

Aziz Alfoudari
  • 5,193
  • 7
  • 37
  • 53
  • You're sure you don't prefer to get your querysets independently and then combine them together as in http://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view? – r_31415 Nov 18 '11 at 19:13
  • What if I filter my A model and then combine it with B? How would I relate to between the two models? It looks like chain just concatenates all elements blindly: http://docs.python.org/library/itertools.html#itertools.chain – Aziz Alfoudari Nov 18 '11 at 22:37
  • 1
    Yes, it seems chain only concatenates your querysets. But what about if you do something like this: B.objects.filter(a__some_field_of_A = 'string'). Then suppose you have an instance b from B that you want. Then you would do: b.a_set.filter(name='somethingelse'). In summary, you ask for instances of B that fulfill a condition through A, then you take one or more, and ask for all the instances of A which are included in B under other condition. That's a relationship between both classes, but I don't how useful you'd find that. In any case, A.B is not an option. – r_31415 Nov 18 '11 at 23:29
  • I have ended up doing it this way, thanks. – Aziz Alfoudari Nov 18 '11 at 23:40

1 Answers1

2

The problem is that, since the relationship is one-to-many, A doesn't have just one B, but rather a b_set

You could so something like:

for b in a.b_set.all():
    b.name

But you can't reference just B because that concept doesn't exist. It would however, if you had used a OneToOneField. Then you could easily do:

a.b.name

Because there's only one B for each A. But, you have to model your object after the actual relationships going on, not how you would prefer the api to work.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • The actual relationship is OneToMany. Do I need to do something in order to be able to use: `a.b_set.all()`? I have tried but it doesn't look like `a` has `b_set`. – Aziz Alfoudari Nov 18 '11 at 22:41
  • `b_set` would be the automatically created relationship. It will be there unless you assigned a `related_name`, in which case, it would be the `related_name` value. – Chris Pratt Nov 21 '11 at 14:12