Is it possible to have a model whose name consists of more than one word e.g. UserProfile and use it in OneToMany relationships with User, for instance, User.hasMany(UserProfile).
Currently, i suspect that either i have not set up correctly something in models or it just is not working like that # this moment. Here is fiddle http://jsfiddle.net/kristaps_petersons/y75eQ/17/.
Help is much appreciated :)
You simply have to snake case the relationShip ids in your fixtures, and I think this will work.
The second thing is to define an id for the users.
In fact, the structures defined in the fixtures must be like the JSON you will receive from the server.
I've updated the fiddle: http://jsfiddle.net/Sly7/y75eQ/19/
Related
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).
I am currently working to write a web app where people fill out the necessary information, and apply to their mentors.
So, at this point, mentors have a model class that is pretty much like the applicant's, so that they can correct the applicant's info without affecting the applicant's original profile.
I will appreciate any helpful comments. Specifically, I am looking for:
-A similar per-exisiting django app that does more or less so I can browse the source.
-Any special Django feature that allows this that I can not aware of.
-General info on how things like these are done in general.
Thank you.
Ad general info)
You would benefit from doing this in a single model (say ApplicationModel), with fields in pairs - field_name_applicant, field_name_mentor.
Then use a CreateView with its fields property set to only the *_applicant fields for the applicant to fill in the applications initially, and an UpdateView with its fields set to the *_mentor fields for the mentor to correct the applicant fields.
Have ApplicationModel.clean() copy all *_applicant field values to their *_mentor counterpart if the later is not set.
Now you have all your business logic in the model where it belongs; quoting a headline in the introduction of Two Scoops of Django:
Fat Models, Helper Modules, Thin Views, Stupid Templates
I'm porting a project from Rails to Django with a legacy database. In Rails I had a polymorphic association that allowed me to add a footnote to any row in the database. I'm trying to implement the same thing in the Django app. I found the documentation on Generic Relations and it looks perfect. Unfortunately, I first need to create new fields in my legacy database to hold the ContentType id for the relevant models. I only used the polymorphic association with 2 tables, so all I need are those two corresponding ids from the Django app, but I can't seem to find the appropriate command for looking up a ContentType id in Django.
Any suggestions are most welcome. I tried searching through previous questions but couldn't seem to find what I am looking for. Thank you very much for you time and help.
from the docs
you can do:
>>> b = Bookmark.objects.get(url='https://www.djangoproject.com/')
>>> bookmark_type = ContentType.objects.get_for_model(b)
>>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
... object_id=b.id)
so just instantiate an instance of your model and then do ContentType.objects.get_for_model(<instance>).id
I think there's a way to pass just the model name, too... let me know if that would work better and I'll try to find it; I've used it in the past.
You can also get ContentType ID without creating an instance, which is more efficient if you don't have and don't need an instance but just want to get ContentType ID by model name.
ContentType.objects.get(model='bookmark').id
Notes : if the name of your model is upper case, please use lower case to search. For example: model = 'bookmark' rather than 'Bookmark'
You don't need to read all this post to help me answer the question, the rest of this post is only the context where the question came, but the general question is:
Where to put business logic that spans multiple models in Django?
some possibilities:
Some View? (I don't think so, it must work in the admin and several views, DRY)
Save methods in model/forms?(how?)
Clean methos in model/forms?(how?)
split the logic and use signals?(how?)
Other?
Context:
I have this models:
Department: Reference different departments in a company (risk, finance,IT,...)
Employee: May belongs to only one department for a period of time and then change to other department.
Project: Each Department can have multiple projects, and a project belongs to multiple departemnts.
Membership: intermediate table between the Employee and Department ManyToMany relationship that includes other fields like join_date and leave_date, important field are fk:Department, fk:Employee
History: intermediate table between Membership and Project that let me know which employee was involved in wish project wen he was working in some department, important fields are fk:Membership, fk:Project.
CurrentProjects: table that relates departments with the projects they are working on currently.
suppose I'm in the Django admin and I go the department Risk, and Risk has currently Project1 and Project2 assigned. when I add a new employee "Jhon Smith" (for example,using an inline form in Department) and press the save button, I want the model History gets updated with this information:
Membership table (only important fields):
pk Department Employee join_date leave_date
20 Risk Jhon Smith xxxx xxxx
History Table (only important fields):
Membership Project
20 Project1
20 project2
I mean when a new employee gets assigned to a new department all the actual projects from that department must be assigned to that Membership employee-department in the table History.
the question is where to put this logic in Django? as you can see this logic involves multiples models, some posibilities are:
In some view (I don think so, it must work in the admin interfase and in other places)
In the clean method of the Membership, Department or Employee model/form?
In the save method of the Membership, Department or Employee model/form?
I have to split the logic and use something like signals? (some example?)
Others?
I'm over complicating everything? =)
Considerations: It would be nice if the code could generate a valueerror at any point in the process and the user/admin could be able to see this error in the unbounded form.
I am just commenting on the aspect of where the logic should live. This all sounds like model logic to me. Django has a slightly mixed concept of MVC. When its purely data relation I believe its all model logic. I would recommend putting the methods as close to the model they affect as possible and simply make the smallest call possible from the triggering model.
If you are very concerned with decoupling the apps, then you could use signals. Instead of Model A knowing it needs to call XYZ during a save, it goes the other way. Model A just emits a signal. XYZ would be responsible for being connected to the signal. You can even make your signal definitions in a completely general project app, in which case neither the triggering or receiving Models know about eachothers actions. It just binds them.
There are some built in signals, such as before and after a save on a model, which means if you are looking for a save trigger you won't have to emit something custom. But lets say at various point of one models logic you need to emit a custom signal like "Name changed", you could emit your own.
Model A
import django.dispatch
name_changed = django.dispatch.Signal(providing_args=["name"])
class ModelA:
...
def foo:
# something happened here
name_changed.send(sender=self, name=the_name)
Model B, C, D
from myApp.modelA import name_changed
name_changed.connect(modelB.handle_name_change, dispatch_uid="my_unique_identifier")
name_changed.connect(modelC.handle_name_change, dispatch_uid="my_unique_identifier")
name_changed.connect(modelD.handle_name_change, dispatch_uid="my_unique_identifier")
Personally I have a habit of creating a utils.py module for apps that need some general "controller model" logic. They are more like actions or helpers.
Maybe the problem is that "history" table you have there. I don't know what kind of information you have in your Project table. But if every project have a start and end date, your history table is handling duplicate information. In this case, if you want to know in which project has worked an employee, you just need to know in which rage of dates this employee have worked for the department and then you need to find the projects of that department that were developed between the previous date range.
I hope you understand my point. If no, please tell me so i can explain it better (maybe with an example).
But as i understand your problem and your models, i think you don't need that history table. It will duplicate information...
So, if your Project model have this information (range of dates) the solution should live in a manager, because it is just a matter of find the information you want that live in multiple tables...
Hope it helps!
In my application I've added a "Facebook Comment Box" (on different pages, for different objects). Each object has its own comments list so I need to provide a unique (across the site) ID for every single one of them.
What would be the best approach for achieving this: An abstract model, from which all other models will inherit? A dummy model with a ForeignKey relation? What are your ideas?
You may want to implement GUIDs:
http://www.codecommit.com/blog/database/are-guids-really-the-way-to-go
Here's a django module that gives you a field for 'em:
http://pypi.python.org/pypi/softwarefabrica.django.utils/
... you can safely use them in URLs -- won't be pretty, but for comments and other things without obvious URL-able titles, GUIDs work out well.
Solved with a dummy model :
http://fromzerotocodehero.blogspot.com/2010/11/providing-uniqueness-of-different.html