popopanda
popopanda

Reputation: 381

Django models, understanding one to one relationship

Im having difficulties understanding what is the purpose of a one to one relationship

I have a form where users fill out the information, and select a benefit type.

For example, I have a model of

class BenefitRequest(models.Model):
    benefitType = models.OneToOneField(BenefitType)
    description = models.CharField(max_length=100)
    benefitAccount = models.ForeignKey(BenefitsAccount

class BenefitType(models.Model):
    benefit = models.CharField(max_length=25)

In my database, for the BenefitType, I have Commute, Fitness, and Ergonomics

However, when I fill out the form and select "Fitness" for PersonA and submit the form, then select "Fitness" again for PersonB and submit it again, it gives me an error stating my BenefitType is already used. Even though it is a new request for another user.

Does that mean in django, a one to one relationship is where a table can have only 1 type of each of another table?

Upvotes: 1

Views: 1976

Answers (2)

keni
keni

Reputation: 1768

It seems what you really want is not a OneToOneField it seems but a ForeignKey. If you want a One-to-many relationship between your model i.e. BenefitRequest can take up any of your benefit type. You need a ForeignKey to BenefitType. Then you can create any BenefitRequest and Choose any BenefitType any number of times:

benefitType = models.ForeignKey(BenefitType)

One way to think of OneToOne field is that they can very well belong to the same model (or database table), they are the same "record" really, separated because of some "constraints". For example, trying to re-use User from django.contrib.auth and knowing you cannot just extend the model without breaking other parts of your application.

Upvotes: 1

J B
J B

Reputation: 400

That's correct. This is not unique to Django; a one to one relationship means each row in one database table is linked to one and only one other row in another table. In a one-to-one relationship between a table named X and a table named Y, each row in X is associated with a row in Y.

For one-to-one fields (in Django, in your case) you have that one field with a value associated with one other field. The Django doc examples refer to a Restaurant that has an Address. This should make the relationship clear: a Restaurant has a single Address (barring some rare real-world exceptions where a building might have more than one address associated with it.)

I suggest looking over the relevant documentation for a more thorough explanation: https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/

If you want your "Benefit Types" to be available to multiple users, you might consider a many-to-one relationship instead.

Upvotes: 3

Related Questions