Reputation: 5578
I have 2 classes:
class Contact(models.Model):
name = model.CharField(max_length=255)
class PhoneNumber(models.Model):
phone = models.CharField(max_length=25)
contact = models.ForeignKey(Contact, related_name="phone_numbers", null=True, blank=True)
When I would like to get a phone number for a contact I can just do this:
contact = Contact.objects.all()[0]
contact_phones = contact.phone_numbers.all()
No sweat here. Now I would like to know what the proper way would be to set a new phone number for a contact.
I have tried to do this:
foo = Contact.objects.create(name="Foo")
contact_phone = PhoneNumber.objects.create(phone="123456789", contact=foo)
This does save the contact and the phone number, but I would just like to be able to create a method inside the Contact class like add_phone()
or something like that.
How would I be able to do that?
Upvotes: 0
Views: 29
Reputation: 599876
You can use the create
method of the reverse manager.
foo.phone_numbers.create(phone='123456789')
Upvotes: 3