6π
β
The two most straightforward ways is by accessing the a
manager of the model object of B
, so:
model_b_object.a.all()
another way to retrieve the related objects, is by filtering the B
model, so:
A.objects.filter(b=model_b_object)
If you defined a through model, for example:
class A(models.Model):
name= models.CharField(...)
class B(models.Model):
a= models.ManyToManyField(
A
through='C'
)
class C(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)
b = models.ForeignKey(B, on_delete=models.CASCADE)
then you can also access this through:
A.models.objects.filter(c__b=model_b_object)
but this only will make the ORM call more complex, and less readable.
1π
Also, you can get data from model B
using model A
as shown below:
for obj in A.objects.all():
print(obj.b_set.all())
And, the code above also works with Middle
model defined between model A
and model B
and the results are the same:
class A(models.Model):
name= models.CharField(...)
class B(models.Model):
a = models.ManyToManyField(A, through="Middle")
class Middle(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)
b = models.ForeignKey(B, on_delete=models.CASCADE)
class Meta:
unique_together = (('a', 'b'))
- [Django]-How can I install plugin into CkEditor, Django
- [Django]-Where in Django can I run startup to load data?
- [Django]-Combining request.data and request.query_params in Django REST Framework
- [Django]-Django all-auth: How to disable automatic login via Google
Source:stackexchange.com