Valueobjects Django

Asked

Viewed 102 times

3

Good morning guys, I’m starting now with Python and Django and I came up with a question in the creation of my models. I’d like to create something like:

Person(models. Model)

  • Name
  • ...
  • Address

Address()

  • Patio
  • Neighborhood
  • ...

That is, separate the address as an Object value so it can be used in more than one template. In the database the fields within the address class will be persisted within the People table and other entities that may arise (Company, Customer, "Anyone who may have an address"). So avoid duplicating all address fields for each model you need.

I saw that I could do setting the Meta of the address to Abstract and inheriting Address Person. Only if I want to do more Valueobjects I will have to inherit from several classes for that, I wonder if there is a more correct way.

Thank you.

3 answers

1

Even if the address is the same among several people, I suggest you leave it as an attribute of the Person class. Unless they live in the same residence/building, we won’t have as many cases. Will facilitate readability and further decrease a ratio between tables in the bank.

Also, if you are working with a form that will send this information, it is difficult to standardize the way the user enters the data ('Rua xx' vs 'R. xx', etc).

1

When I find myself in this kind of situation, I always have two options:

  1. Relate the item
  2. Create a separate table for the address and add the foreign key to the client.
  3. Create an Address table and make the Client table inherit from Address. Then it would have the address fields, plus the client fields.

0

I think what you are looking for is a Many-to-one relation. You could create a separate "Address" model and create a field Foreign key in the model "Person"

class Pessoa(models.Model):
    [...]
    endereco = models.ForeignKey('Endereco', on_delete=models.CASCADE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.