Django, how to have an array in model without M2M? - sql

I want my model to have an array of other model's instances. Let me explain.
I have a Company model which has a localizations field which is supposed to be a set/array of addresses. Since one address can only be for one Company, M2M relationship seems wrong here.
When Company gets deleted, all of its localizations should also be deleted.
How do I accomplish that? (I don't use Postgres)

In this situation you want a ForeignKey (which is a many-to-one relationship). See the code below:
class Company(models.Model):
...
class Address(models.Model):
company = models.ForeignKey(Comapny, on_delete=models.CASCADE, related_name="localizations")
address_line_1 = models.CharField(max_length=255, blank=False)
# Other fields you want
...
Each Address points to one Company instance. But there is no limit on how many Addresss can point to a Company. In this sense, a company "has" many addresses.
The related_name="localizations" argument, means that you can do company.localizations to get an array of the Address instances that point to that company.
Finally, on_delete=models.CASCADE means that if you delete a Company instance, the Address instances that point to it will also be deleted.

Related

Multiple addresses as Entity or ValueObject?

I have a registration form for users that can insert multiple addresses.
I take User as an entity but I am not sure about collections of addresses. if it was only one address I would take it as ValueObject but I am not sure what about collections of addresses. if I have to take them as ValueObject how can I store them in tables, do I need to define a new table for it, if Yes they get Ids that are wrong for ValueObject.
Collection of addresses is fine as a value object.
The fact that your storage implementation requires multiple rows (with identifiers?) is an implementation detail of storage that has nothing to do with the model of your domain.

Is my relation a one-to-many or a many-to-many?

I have a model called Addresss which as the name sounds, is a list of addresses.
These addresses can belong to a Client and a client can have many of these addresses.
To link these addresses to the client, I will simply have a table called ClientAddress with 3 columns: id, client_id and address_id.
Is this an example of a one to many or a many-to-many relationship? I currently have it setup as a ManyToMany relationship in Phalcon however I'm not sure if it should actually be One to Many.
It's a one-to-many relation. One client (can) have multiple addresses. One address belongs to only one client.
Regarding your clientAddress table, I'd get rid off it as you can store the client id on the adress table.
If, as your tags suggest you're using phalcon and decide do go with phalcon's orm you should have a look at the documentation : Working with Models
Its all depends how you are thinking about your Entities
Lets start from Client
We would like to store information about Client. Now if our Client has only one specific Location then we have two options. We can directly store the Address information in same table as-
clients table
id, f_name, l_name, address, current_city, home_city, etc....
In this case there is nothing about Relation
If you are interested then you can split this table and store Location information on other table which you may name as addresses. Then the Relation between Client and Address will be one-to-one relation.
Now, if our Client has different office on different Location then it is mandatory to store Location information on different table. Then the Relation will be one-to-many as our Client has different `Location'.
Now, if we have many Client on same Location (same building may be) and our Client has many office in many Location then it will be as many-to-many relation. As Client hasMany Address and Address hasMany Client we new a pivot or intermediate table to hold our Relation information.
It depends on quite how complex your model is likely to become.
Suppose your "clients" are branches of a national company. Eech "client" may then have multiple adrresses - delivery address and billing address for instance. And equally, since the accounts-payable function may be centralised to either a regional or national branch (which may itself have, or not have a "delivery address)" the billing address is likely to be shared amongst many "clients."
So, in this scenario, many-to-many.

ER Diagram flaws

I have the following ER Diagram for a bank database - customers may have several accounts, accounts may be held jointly by several customers, and each customer is associated with an account set and accounts are members of one or more account sets. What design rules are violated? What modifications should be made and why?
So far, a few flaws I'm not sure about are:
1) Redundant owner-address attribute in AcctSets Entity.
2) This ER does not include accounts with multiple owners with different addresses.
My Question is: How would I go about fixing these flaws and/or other flaws that I may be missing from my analysis? Thanks!
I'm not sure what the AccountSet entity does.
You have a many to many relationship with Customers and Accounts. Therefore, you need a CustomerAccount entity that ties a customer to one or more accounts, and an account to one or more customers.
CustomerAccount
---------------
CustomerAccountKey
CustomerKey
AccountKey
This entity would be accessed by either the CustomerKey, to get the accounts for a customer, or the AccountKey, to get the customers for an account. The CustomerAccountKey is only used to cluster the data on a database.
The CustomerKey - AccountKey combination in the CustomerAccount entity is unique.
If you want more than one address for a customer, that that becomes a one to many relationship between the Customer entity and the Address entity. This allows customers to have a summer address and a winter address, as one real life example.
You haven't states a reason for having the abstraction Account Sets. You need an intersection between Customer and Account, since your business rules say many to many, but why have an intervening abstraction?
Even assuming you keep it, the attribute owner address doesn't belong on the abstraction/intersection entity between Account and Customer (i.e. Account Set). That just doesn't make sense. There is nothing in your stated rules nor in common experience to suggest that customer address has any functional dependency on the relationship between an account and a customer. If anything, it would be functionally dependent on the customer alone. As it stands, you are modelling this dependency to be multi-valued, so the address isn't even fully functionally dependent on the customer. The only 3NF place to put it would be on the Addresses entity type.
You should consider a better name than Addresses. First, your entities should be named for the object they represent. Resist the urge to use plural nouns. The entity type is not a collection. The table that implements the entity type will be a collection of your entity instances, but that goes without saying and plural noun naming will just lead you into confusion when you are thinking about cardinalities of relationships. I'd suggest Location as an entity type name, with address as an attribute. When you go beyond the conceptual level address is almost certainly going to have to be decomposed.
Other than that, you are on a pretty good track, based on the business rules you've cited.

database optimization issue

i have a table Students which contains the following colums:
Id,FirstName,LastName,Adress.
The colum Adress will contain just the street adress.
the question is: will it be better for the database optimization to isolate the column Adress in a different table?
Yes. If you seperate it into another table, you can have more than one address per person. If you seperate it to two different tables, an Address table and a StudentAddress table to map the two together, you can make sure that a single address is shared between people or even track a history of addresses for one person. Further, in a seperate table you can break the address down into columns so that you can easily search by City or Province or Country.
You can't do any of that putting an Address into a single column with the Student table.
It depends on how you are going to treat that Address. If you will need to treat it as different entity, i.e. link single address to several Students or vice versa e.t.c., then you should do normalization.
If address is only attribute of entity student then leave it as is.
For full proper data structures to manage addresses: THe Data Model Ressource BOok, Volume 1. It is a LOT more complicate to get right than you think.

How would you model a "default child" flag with an ORM?

I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a many-to-many relationship between a parent class and its children.. I was wondering, what would be a simple way to express the concept "one of the children is the default/main one"?
For example, I'd need to persist the following:
This Person instance has Address X and Y, the main one is Y.
I saw this implemented using a "middle" class like "PersonAddressRelation" that would contain "Person", "Address" and the "main" flag, but I think it looks a bit cumbersome.. Is there a better way?
The simplest way would be to have a join table, PersonAddressRelation, and also a DefaultAddress column on the Person table that keys to the Address table.
A couple of remarks.
M:N relationships don't specify 'parent' and 'child', as there's no parent nor a child: there are simply two entities having an m:n relationship via a 3rd entity (the intermediate entity).
'Address' is in general not a valid entity type, as semantically it has no identity, similar to a 'name' has no identity (first name, last name). You'll see this when you look at re-using an entity instance of type Address: you won't do that in general. (though you will re-use a Customer entity instance for example, when the customer has multiple orders)
You want to specify an attribute on the M:N relationship (default), as it belongs there. This means that the relationship itself forms an entity (which is the intermediate entity, often it has just two FK fields forming the PK). This is called an 'objectified relationship', as the relationship itself is seen as an entity. Other examples of this are Employee m:n Department and you want to specify the StartDate an employee started for a department the employee works for.
So in general: create the intermediate entity, as it in general should be there, and add the attribute there. In this particular case with Address, be really sure you are re-using Address instances among related entities (Person). If not, merge Address with Person OR if a person can have multiple addresses, create a simple 1:n relationship between Person - Address, to normalize it out, though don't be afraid to merge address data into the entity it is related to, as often address data is really not re-used (so your m:n relationship is really not there: there's no Address instance which is related to multiple person instances.