I'm using Silex and Doctrine to create an API, which makes use of Doctrine Associations. I'm using JMSSerializer to serialize entities.
All entities are returned as nice JSON objects except one, which has a ManyToOne association.
I find when this particular entity is serialized, it is actually the serialized Proxy class, including properties such as:
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true,
Why am I getting the proxy class in this case instead of the Entity? I've tried calling methods on the Objects in the application before serialization in an attempt to load the complete Entities, but I always seem to get the Proxy class.
My interim solution was to change the ManyToOne association to a ManyToMany and implement a ManyToOne constraint in the Model.
This is not elegant but it does seem to prevent the ORM from providing a proxy class and provide useful entities for both sides of the association when one is fetched.
Related
When defining models with foreign keys, Django asks the user to specify them as strings in order to avoid issues with circular dependencies.
What's the algorithm it uses to create the related models after parsing the strings? I've looked through Django's source code but haven't been able to understand it.
I thought it'd create a graph out of the models, topologically sort it and start by instantiating the models that don't depend on the rest. This, however, seems too simplistic since the graph may not be a DAG, as in the following example:
class ModelA:
b = ForeignKey(ModelB)
class ModelB:
c = ForeignKey(ModelC)
class ModelC:
a = ForeignKey(ModelA)
Thank you!
When you pass a string, Django first tries to look up the model. If it exists and it is registered, it is replaced immediately.
It the model isn't registered yet, a lazy operation is added to the app registry. For example, this method is used to solve the to part of a relation. The to attribute is replaced in-place with the actual model, and the reverse relation is added to the to model.
Whenever a new model class is defined, the metaclass registers the model in the app registry. The app registry the goes through the list of pending operations for that model, and fires each of them.
So, for each valid string reference, when the field is instantiated, the target either exists and the string is immediately replaced with the model class, or the target doesn't exist yet, but a lazy operation is used to replace the string with the model class when that model class is created and registered.
If you have a circular reference of, say, 2 models, the first model class will add a lazy operation. The second model class can immediately resolve its reference to the first model class, and then activates the lazy operation to resolve the reference from the first model class to the second model class.
I want to add a layout model to my website (a general settings file), and I want it to be available in the admin interface for configuration.
class Layout(...Model):
primary_header
logo_image
...
This structure shouldn't saved be in a table.
I am wondering if there is a built-in feature that can help me do this.
Thanks
My use case is a configurable layout of the website. Wordpress style. I would like to store that data in a concrete class, without having to implement the file /xml serialization myself.
What about an abstract model? It does not save in the database and is meant to be subclassed, but you are allowed to create instances of it and use its attributes. I assume you want some kind of temporary data structure to pass around that meets the requirements of a model instance.
class Layout(models.Model):
class Meta:
abstract = True
If you for some reason need actual concrete models, and are fine with it creating tables for them, you could technically also re-implement the save() method and make it no-op.
I don't really understand where and how you will be using this, but this is indeed a model that doesn't save.
Personally, I have actually used models that aren't intended to be saved, in a project that uses mongodb and the nonrel django fork. I create models that are purely meant to be embedded into other models as nested sub-documents and I never want them to be committed to a separate collection.
Update
Here is another suggestion that might make things a whole lot easier for your goal. Why not just use a normal django model, save it to the database like normal, and create a simple import/export function to save it out to XML or read into an instance from XML. That way you get 100% normal admin functionality, you can still query the database for the values, and the XML part is just a simple add-on. You can also use this to version up preferences and mark a certain one as active.
I am quite new to Doctrine 2. I am wondering if there is an easy way / what the beast way is to include fields such as date_created, date_modified, author_id etc across all of my entities - or do I need to paste these fields into each yaml file. Would be great to specify these globally so that new fields can be easily added etc.
You can use a mapped superclass - Essentially you would create a superclass where you put your shared properties and add mappings to it, then have your actual entity classes inherit it.
See manual section Inheritance Mapping: Mapped superclasses
I'm working on a Symfony2/Doctrine2 project which handles 2 databases on MSSqlServer.
The first database A_db has a table forms and the second one B_db has people. All my entities are defined with annotations.
I need to get all forms from forms related to people as I will explain in following lines.
I've spent some time reading related answered questions:
Most likely what I need Using EntityManager inside Doctrine 2.0
entities!
Of course, a service! Doctrine2 Best Practice, Should Entities use Services?
Services/Repositories/Whatever Using the Data Mapper Pattern, Should the Entities (Domain Objects) know about the Mapper?
So I decided that a service might be the best way to handle my needs. But it makes no clear to me how actually get this done. I mean, where to put my service class, how to define it in config.yml, how into people entity...
My wish is to set up a full service (assuming its the best implementation) to perform something like:
foreach($onePeple->getForms() as $form) {/* some code with form */}
In case service implementation for doctrine is not the best practice, then what would it be and how can I make it work?
What you're asking there is possible using the entities alone - so long as you define a relationship such as this on the Form entity:
/**
* #OneToMany(targetEntity="Form", mappedBy="User")
*/
protected $Forms;
And on the User entity:
/**
* #ManyToOne(targetEntity="User", inversedBy="Forms")
*/
protected $User;
Then you can simply load a User entity (through a service, a repository or however you wish) and then access all the forms belonging to that user through $userObj->Forms (if using magic __get on your entities, if not then using a getter method, again down to your preference). Forms is an instance of an object implementing the Doctrine\Common\Collections\Collection interface (since it is a to-many relationship) which is iterable using a foreach.
In projects I have worked on using Doctrine2, we typically use our services for getting, saving and deleting entities, along with listing entities of a type (we call them index methods). This way you can tie in extra functionality required in saving, such as updating other entities which are closely associated and so on. These services are tied to the persistence layer and contain a reference to the entity manager, leaving the entities themselves isolated and testable.
We've also had the argument of whether to put this kind of logic in repositories or services, but that is more a case of personal preference and/or project requirements.
One thing to note - services you build are not going to be linked into Doctrine. It is unaware of your service layer (it's just some userland code) so it is up to you to link it in a meaningful and clean manner. Essentially you'd want something where you could pass the entity manager in through the constructor of the service and have some kind of base service class capable of operating on all entities, which could then be extended with special logic on a per-entity basis. Repositories, however, are intrinsically linked into Doctrine, so if that is what you want then it might be the best solution. We tended to use services as they are then purely related to implementing the business rules and so on, leaving the repositories to be used as a component of the persistence layer.
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