7👍
✅
One way:
group = Group.objects.get(pk=group_id)
contacts_in_group = Contact.objects.filter(group=group)
Another, more idomatic, way:
group = Group.objects.get(pk=group_id)
contacts_in_group = group.contact_set.all()
contact_set
is the default related_name
for the relation as shown in the related objects docs.
If you wanted to, you could specify your own related_name
, such as related_name='contacts'
when defining the field and then you could do group.contacts.all()
To add a new Contact to a group, you just need to assign the relevant group to contact via the group field and save the Contact:
the_group = Group.objects.get(pk=the_group_id)
newcontact = Contact()
...fill in various details of your Contact here...
newcontact.group = the_group
newcontact.save()
Sounds like you’d enjoy reading the free Django Book to get to grips with these fundamentals.
3👍
You will need to modify your code as shown below:
contacts = group.contact_set.all()
See the relevant documentation for more details.
- [Django]-Django query: Joining two models with two fields
- [Django]-Django model.save() not writing to database
- [Django]-Access Django App on AWS ec2 host
Source:stackexchange.com