Johan Vergeer
Johan Vergeer

Reputation: 5578

Django how to add an instance to reversed ForeignKey

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

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599876

You can use the create method of the reverse manager.

foo.phone_numbers.create(phone='123456789')

Upvotes: 3

Related Questions