Django 2.1: How to get a list of objects that in each object, contains the objects that have a foreign key...











up vote
0
down vote

favorite












I have these two classes:



Class A:
data

Class B:
a = models.ForeignKey(A)


How can I get an array of A in which each A contains the B's related to them?



I need it because I must return the two tables joined in a JSON.










share|improve this question









New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • With the above modeling, an A can have zero, one, or more Bs related to A.
    – Willem Van Onsem
    Nov 17 at 15:10










  • None of your classes is a Django model.
    – Klaus D.
    Nov 17 at 15:19










  • Because it's pseudocode
    – Jayem97
    Nov 17 at 15:23















up vote
0
down vote

favorite












I have these two classes:



Class A:
data

Class B:
a = models.ForeignKey(A)


How can I get an array of A in which each A contains the B's related to them?



I need it because I must return the two tables joined in a JSON.










share|improve this question









New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • With the above modeling, an A can have zero, one, or more Bs related to A.
    – Willem Van Onsem
    Nov 17 at 15:10










  • None of your classes is a Django model.
    – Klaus D.
    Nov 17 at 15:19










  • Because it's pseudocode
    – Jayem97
    Nov 17 at 15:23













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have these two classes:



Class A:
data

Class B:
a = models.ForeignKey(A)


How can I get an array of A in which each A contains the B's related to them?



I need it because I must return the two tables joined in a JSON.










share|improve this question









New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I have these two classes:



Class A:
data

Class B:
a = models.ForeignKey(A)


How can I get an array of A in which each A contains the B's related to them?



I need it because I must return the two tables joined in a JSON.







python django






share|improve this question









New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 17 at 19:36









user6910411

31.8k76692




31.8k76692






New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 17 at 15:09









Jayem97

32




32




New contributor




Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Jayem97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • With the above modeling, an A can have zero, one, or more Bs related to A.
    – Willem Van Onsem
    Nov 17 at 15:10










  • None of your classes is a Django model.
    – Klaus D.
    Nov 17 at 15:19










  • Because it's pseudocode
    – Jayem97
    Nov 17 at 15:23


















  • With the above modeling, an A can have zero, one, or more Bs related to A.
    – Willem Van Onsem
    Nov 17 at 15:10










  • None of your classes is a Django model.
    – Klaus D.
    Nov 17 at 15:19










  • Because it's pseudocode
    – Jayem97
    Nov 17 at 15:23
















With the above modeling, an A can have zero, one, or more Bs related to A.
– Willem Van Onsem
Nov 17 at 15:10




With the above modeling, an A can have zero, one, or more Bs related to A.
– Willem Van Onsem
Nov 17 at 15:10












None of your classes is a Django model.
– Klaus D.
Nov 17 at 15:19




None of your classes is a Django model.
– Klaus D.
Nov 17 at 15:19












Because it's pseudocode
– Jayem97
Nov 17 at 15:23




Because it's pseudocode
– Jayem97
Nov 17 at 15:23












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










First set the back relation of a and then migrate the database:



Class A(models.Model):
data

Class B(models.Model):
a = models.ForeignKey(A, related_name='b_relations', null=False, blank=False, on_delete=models.CASCADE)


Now you can access the back relation. You need to call .all() on b_relations because it is lazy loaded.



A.objects.first().b_relations.all()


To get json data I suggest to use django rest framework's ModelSerializer:



class BSerializer(serializers.ModelSerializer):
class Meta:
model = B
fields = (
'pk', # primary key
'a',
)
depth = 0

class ASerializer(serializers.ModelSerializer):
b_relations = BSerializer(many=True, read_only=True))

class Meta:
model = A
fields = (
'pk', # primary key
'b_relations',
)
depth = 0


To get json data:



a_relations: QuerySet = A.objects.all()
serializer = ASerializer(a_relations, many=True)
json_data: Dict = serializer.data


In case you've never used Django Rest Framework: Django Rest Framework - Getting Started



Have fun!






share|improve this answer

















  • 1




    Thank you very much, it's been very helpful and now it works!
    – Jayem97
    Nov 17 at 16:00











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Jayem97 is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352492%2fdjango-2-1-how-to-get-a-list-of-objects-that-in-each-object-contains-the-objec%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote



accepted










First set the back relation of a and then migrate the database:



Class A(models.Model):
data

Class B(models.Model):
a = models.ForeignKey(A, related_name='b_relations', null=False, blank=False, on_delete=models.CASCADE)


Now you can access the back relation. You need to call .all() on b_relations because it is lazy loaded.



A.objects.first().b_relations.all()


To get json data I suggest to use django rest framework's ModelSerializer:



class BSerializer(serializers.ModelSerializer):
class Meta:
model = B
fields = (
'pk', # primary key
'a',
)
depth = 0

class ASerializer(serializers.ModelSerializer):
b_relations = BSerializer(many=True, read_only=True))

class Meta:
model = A
fields = (
'pk', # primary key
'b_relations',
)
depth = 0


To get json data:



a_relations: QuerySet = A.objects.all()
serializer = ASerializer(a_relations, many=True)
json_data: Dict = serializer.data


In case you've never used Django Rest Framework: Django Rest Framework - Getting Started



Have fun!






share|improve this answer

















  • 1




    Thank you very much, it's been very helpful and now it works!
    – Jayem97
    Nov 17 at 16:00















up vote
0
down vote



accepted










First set the back relation of a and then migrate the database:



Class A(models.Model):
data

Class B(models.Model):
a = models.ForeignKey(A, related_name='b_relations', null=False, blank=False, on_delete=models.CASCADE)


Now you can access the back relation. You need to call .all() on b_relations because it is lazy loaded.



A.objects.first().b_relations.all()


To get json data I suggest to use django rest framework's ModelSerializer:



class BSerializer(serializers.ModelSerializer):
class Meta:
model = B
fields = (
'pk', # primary key
'a',
)
depth = 0

class ASerializer(serializers.ModelSerializer):
b_relations = BSerializer(many=True, read_only=True))

class Meta:
model = A
fields = (
'pk', # primary key
'b_relations',
)
depth = 0


To get json data:



a_relations: QuerySet = A.objects.all()
serializer = ASerializer(a_relations, many=True)
json_data: Dict = serializer.data


In case you've never used Django Rest Framework: Django Rest Framework - Getting Started



Have fun!






share|improve this answer

















  • 1




    Thank you very much, it's been very helpful and now it works!
    – Jayem97
    Nov 17 at 16:00













up vote
0
down vote



accepted







up vote
0
down vote



accepted






First set the back relation of a and then migrate the database:



Class A(models.Model):
data

Class B(models.Model):
a = models.ForeignKey(A, related_name='b_relations', null=False, blank=False, on_delete=models.CASCADE)


Now you can access the back relation. You need to call .all() on b_relations because it is lazy loaded.



A.objects.first().b_relations.all()


To get json data I suggest to use django rest framework's ModelSerializer:



class BSerializer(serializers.ModelSerializer):
class Meta:
model = B
fields = (
'pk', # primary key
'a',
)
depth = 0

class ASerializer(serializers.ModelSerializer):
b_relations = BSerializer(many=True, read_only=True))

class Meta:
model = A
fields = (
'pk', # primary key
'b_relations',
)
depth = 0


To get json data:



a_relations: QuerySet = A.objects.all()
serializer = ASerializer(a_relations, many=True)
json_data: Dict = serializer.data


In case you've never used Django Rest Framework: Django Rest Framework - Getting Started



Have fun!






share|improve this answer












First set the back relation of a and then migrate the database:



Class A(models.Model):
data

Class B(models.Model):
a = models.ForeignKey(A, related_name='b_relations', null=False, blank=False, on_delete=models.CASCADE)


Now you can access the back relation. You need to call .all() on b_relations because it is lazy loaded.



A.objects.first().b_relations.all()


To get json data I suggest to use django rest framework's ModelSerializer:



class BSerializer(serializers.ModelSerializer):
class Meta:
model = B
fields = (
'pk', # primary key
'a',
)
depth = 0

class ASerializer(serializers.ModelSerializer):
b_relations = BSerializer(many=True, read_only=True))

class Meta:
model = A
fields = (
'pk', # primary key
'b_relations',
)
depth = 0


To get json data:



a_relations: QuerySet = A.objects.all()
serializer = ASerializer(a_relations, many=True)
json_data: Dict = serializer.data


In case you've never used Django Rest Framework: Django Rest Framework - Getting Started



Have fun!







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 17 at 15:30









Tobias Ernst

633510




633510








  • 1




    Thank you very much, it's been very helpful and now it works!
    – Jayem97
    Nov 17 at 16:00














  • 1




    Thank you very much, it's been very helpful and now it works!
    – Jayem97
    Nov 17 at 16:00








1




1




Thank you very much, it's been very helpful and now it works!
– Jayem97
Nov 17 at 16:00




Thank you very much, it's been very helpful and now it works!
– Jayem97
Nov 17 at 16:00










Jayem97 is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















Jayem97 is a new contributor. Be nice, and check out our Code of Conduct.













Jayem97 is a new contributor. Be nice, and check out our Code of Conduct.












Jayem97 is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352492%2fdjango-2-1-how-to-get-a-list-of-objects-that-in-each-object-contains-the-objec%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin