Django Many to Many - polymorphic - django

In a Django application, I have three models:
Service
Product
AppliedTax
I want to create a many-to-many relationship between Service and AppliedTax and between Product and AppliedTax. Normally I would have an intermediate model (i.e. AppliedTaxTaxable) with three fields (applied_tax_id, taxable_type and taxable_id) and taxable_type + taxable_id would be a composite foreign key for each related model with taxable_type having as value the name of the related model (Service or Product in my case) and the taxable_id field the id of the related record of the respective model.
I understand how to make it work with raw queries, but Is there a "Django" way to do that with a ManyToMany relationship? So far I had no luck with that. I don't have much experience with Django, but I hope there is a way to do that without using raw queries.
Help :)

Well, after some thought, I did a better search and stumbled upon django-polymorphic. Here is a pretty straightforward explanation on how it works, for a basic set up and it does what I am describing in my question. The implemented schema differs a bit from what my description, but in the end we will home one intermediate table for all associated models.

Related

Why there isn't a "ListField" in Django?

I have a model that has a Charfield (let's name it advantages) with a choices attribute. After a while, I've decided that this field should be "upgraded" to some kind of ListField, since more than one choice can be selected.
From what I have searched, I have two options:
1 - Create a new model, and use a ManyToManyField in the first model referencing this new model. This way, the "multiple select" default field used in admin will be rendered. Life is good.
2- Create a custom field that saves my field as a string with some kind of separator.
These two approaches are summarized in What is the most efficent way to store a list in the Django models? and the 2nd approach in more examples: How to create list field in django, http://cramer.io/2008/08/08/custom-fields-in-django/, https://djangosnippets.org/snippets/1200/, https://djangosnippets.org/snippets/1491/
Fact is: I don't want to create another model just to have the ManyToManyField. This is a controlled list of choices that I have (and don't want people adding new items) and think that creating a table for this is overkill (although I can create a fixture to this table and not register the model in admin.py, so people wouldn't be adding new items. But I don't know how would migrations work when changing these values in fixtures, when in the past I would just chance the choices tuple in my model definition).
...and creating a new custom field, I don't know. This seems like problems in the long run since I don't know the implications, problems when upgrading Django, etc.
Why there isn't a built in ListField? Which problems do you see in the long run for the two approaches I'm thinking of? I'm planning to do the first but I'm a little lost about migrations.
django.contrib.postgres has an ArrayField.
You seem to not be willing to create a new table with only the List inside (because it would be "overkill"), but what you are suggesting is to copy/paste the same exact values in all the entries of your table, which isn't a good model solution in my opinion.
I'd advise to go for the ManyToMany (or any other implementation doing the trick with another table).

Creating Model Relationships Via Forms

What is the defacto way of creating model relationships in Django via frontend forms.
For example a user signs up for service using a form, they start a quote.
In getting a quote they can select and add products to their quote specifying variable such as sizes in this process.
This is modelled with relevant User, Quote, Product models and relevant relationships.
I am trying to work out the best way that these are linked together by frontend forms and views.
Would I load into the quote form a hidden field for the related user_id for example, which I can then process manually to form the one-to-many relationship.
I am just wondering if this is something accounted for within forms or if I have to manually create the forms to achieve my goal.
This is one of the more complicated things to try and achieve but there are several things in Django which will help you.
You're going to need a ManyToMany field on the Quote model to link the Products to it.
This can be displayed in forms simply via a ModelMultipleChoiceField:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelmultiplechoicefield
... which is just renders a basic multiple select list of existing products.
The interface you want probably looks more like an inline formset however. The complication here is that they are designed for ForeignKey relations rather than ManyToMany.
Under the covers, a ManyToMany relation is actually just two ForeignKey relations, via an intermediate 'through' model. We can exploit this to build an inline formset on the through model, see this answer:
https://stackoverflow.com/a/10999074/202168
You'll note the caveat in that answer, the inline rows won't know which Quote they belong to unless you override some code.
You may like to look at some helper apps which provide custom widgets for ManyToMany fields:
https://code.google.com/p/django-ajax-filtered-fields/
http://django-autocomplete-light.readthedocs.org/en/latest/

Differences between one-to-one and foreign key relationships?

Can someone explain the significance of specifying a relationship in a Django model as one-to-one as opposed to just a foreign key?
Specifically, I'm wondering what advantages you get from specifying a relationship as 1-1, if any.
Thanks so much.
The OneToOneField evolved in Django after 'ForeignKey'. Conceptually a ForeignKey with unique=True constraint is similar to OneToOneField.
So if you want to ensure that every picture has one user and vice-versa use a OneToOneField.
If you want one user to have any number of pictures use a ForeignKey.
The way things are selected are also different. In case of doing OneToOneField, you can do user.picture and get the picture directly. In case of ForeignKey you will do user.picture_set[0] to get the first picture or access all the pictures associated with that user.
MultiTableInheritance implicitly uses OneToOneField internally and you can see where the concept originated from.
The additional constraints of a 1-1 provide a tighter and richer conceptual model but can also provide insight that can allow for more intuitive retrieval. As a many to one represents a parent/collection relationship there is an unclear cost associated with the retrieval of any given collection for a particular entity. Since a 1-1 provides a flat mapping there is also a flat cost of retrieval. This would lead to things like preferring eager fetching when relevant, as the join will be be able to be easily optimized and the resultant data set will be a known size.
They are not the same; think about it:
If you have a one-to-one relationship between a User and a Picture, you are saying that a user can only have one picture (and a picture can only have one user). If you were to have a Picture with foreign key to User, then you are saying that a picture must have exactly one user, but a user may have 0, 1 or many pictures.
Django's Foreign Key is a many to one relationship. Now, the difference between them is the same as the difference between a One-To-One and Many-To-One relationship. For example, if you have User and Profile entities. You would like to add a constraint that each User could have one and only one Profile. Then, using a django's one to one field would create a restriction on the database level so, that you won't be able to relate User to multiple Profiles or vice-versa. Where as using Foreign Key wouldn't provide this constraint.

Django end-user defined fields, how to? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Django dynamic model fields
Good Morning guys!
Scenario is the following. For some models on Django, I would like to allow the end user to define his own fields. It would be great if I could keep all Django awesome features like the ORM, so I can still do calls like field__gte to search on the model, still have field validation according to field type, etc. I've thought about two ways of doing this, and I'm more than open for new suggestions. Any feedback would be VERY appreciated.
The first approach, is the Entity-Attribute-Value ( http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model ), which django already has an app for. See http://code.google.com/p/django-custom-field/
I think this would be an OK solution, but I lose the ability to do "mymodel.objects.filter(custom_field_x=something)". Maybe there's a way to regain the ORM, any ideas? But I've heard so many bad stories about this method that I'm little scared to use it.
The second approach would be to have a database table for each of the users (probably no more than a 1000). I've read django has something in the lines of inspectdb, which actually checks which fields are there and produces the model for you. This could be useful but I think maybe I should store the fields this particular user has created and somehow dinamically tell django, hey, we also have this fields in this model. Is this possible? I know it's generally bad to have different tables for each user, but considering this scenario, how would you guys rate this method, would it be ok to have one table for each user?
The model that requires custom fields is for example Person. They might want a custom field to store address, blood type, or any other thing.
MANY THANKS in advance! Have a nice sunday!
Very similar: How to create user defined fields in Django -- but only talks about the EAV, which I would like to avoid. I'm open for new ideas!
One approach is to use a NoSQL document-based solution such as MongoDB which allows you to store objects that have a fluid structure (no such restrictions as pre-defined columns).
Pros:
No restriction on custom field types, number of types of fields, etc.
Retains ORM functionality (django-mongodb)
Other various benefits of NoSQL - which you can read about online
Avoids EAV
Cons:
Need to setup NoSQL server
Additional knowledge required on NoSQL concepts (documents vs. tables)
You may have to maintain two databases - if you decide not to migrate your entire solution to NoSQL (multi-db)
EDIT:
After reading the comments its worth pointing out that depending on which NoSQL solution you go with, you may not need reversion support. CouchDB, for example has built in support for document versioning.
what about creating another model for storing user_defined_fields?
class UserDefinedField(models.Model):
#..................
user = models.ForeignKey(User)
field_name = models.CharField(max_length=50)
field_value = models.TextField()
Then you can do UserDefinedField.objects.filter(field_name=some_name,field_value=somevalue)

Understanding Django's Intermediary Models

I'm trying to understand the purpose of Django Intermediary Models.
Conceptually, they seem to be equivalent to association classes in UML class diagrams. Is there any fundamental difference between the two that I should be aware of?
In spite of the apparent similarity, I've found several resources explaining the purpose of intermediary models, but none of them made any reference to "association classes", which makes me somewhat suspicious.
You're not likely to find any comparisons with UML diagrams in the Django literature - UML modelling isn't really a big thing in the Python world, in my experience.
But looking at your diagram, I'd agree that the concept does seem very similar. Don't forget that the ORM is just that, a mapping of relational concepts onto objects: in this case, the through table maps the intermediary table that is always created in a many-to-many relationship. The only difference is that you only need to specify it manually if you want to add extra information to that relationship, like the enrollment date in your link. If you don't need the extra fields, you don't need to specify the intermediary model, but the table still exists, containing just the foreign keys to each end of the M2M relationship.
They're used to store additional data about a many-to-many relationship. I'm sure this is blasphemy, but I think the best example is from the Ruby on Rails guides, which uses the association between patients and doctors. A doctor has many patients through appointments; a patient has many doctors through appointments as well; but you can't model this relationship directly, because an appointment also has a date and time.
I think you are right that conceptually, they server a similar purpose to association classes in UML.
This is how many-to-many relation is to be implemented in any relational database, it is a fundamental part of relational database design. So I suggest to learn about database design principles first because knowing how database works is necessary for using ORM properly anyway.
wikipedia on Many-to-many