Django models and auto created tables - sql

I'm using django for my project, its all going well except its table handling.
Autocreated tables are great for people who don't want to make raw queries and are not interested in adding and deleting columns. But for me, I want to have complete control over my database.
class Partner(models.Model):
software = models.ManyToManyField(Software)
This creates:
partner_partner
partner_partner_software
Second table to handle manytomany relation.
This kind of behaviour makes it complicated for me to observe and understand my table structure.
I think this allows me to do it:
partner = Partner.objects.get(pk=1)
software = partner.software
if I don't use manytomany like relations and instead of above usage,
partner = Partner.objects.get(pk=1)
software = Software.objects.get(name = partner.software)
You think using this kind of technique is the best choice in this case?

I used Django and I have complete control over my tables. I just set it up in a way that it lets Django handle the CMS part and CodeIgniter handles the site.

Related

Automatically connect SQL tables based on keys

Is there a method to automatically join tables that have primary to foreign relationship rather then designate joining on those values?
The out and out answer is "no" - no RDBMS I know of will allow you to get away with not specifying columns in an ON clause intended to join two tables in a non-cartesian fashion, but it might not matter...
...because typically multi tier applications these days are built with data access libraries that DO take into account the relationships defined in a database. Picking on something like entity framework, if your database exists already, then you can scaffold a context in EF from it, and it will make a set of objects that obey the relationships in the frontend code side of things
Technically, you'll never write an ON clause yourself, because if you say something to EF like:
context.Customers.Find(c => c.id = 1) //this finds a customer
.Orders //this gets all the customer's orders
.Where(o => o.date> DateTIme.UtcNow.AddMonths(-1)); //this filters the orders
You've got all the orders raised by customer id 1 in the last month, without writing a single ON clause yourself... EF has, behind the scenes, written it but in the spirit of your question where there are tables related by relation, we've used a framework that uses that relation to relate the data for the purposes thtat the frontend put it to.. All you have to do is use the data access library that does this, if you have an aversion to writing ON clauses yourself :)
It's a virtual certaintythat there will be some similar ORM/mapping/data access library for your front end language of choice - I just picked on EF in C# because it's what I know. If you're after scouting out what's out there, google for {language of choice} ORM (if you're using an OO language) - you mentioned python,. seems SQLAlchemy is a popular one (but note, SO answers are not for recommending particular softwares)
If you mean can you write a JOIN at query time that doesn't need an ON clause, then no.
There is no way to do this in SQL Server.
I am not sure if you are aware of dbForge; it may help. It recognises joinable tables automatically in following cases:
The database contains information that specifies that the tables are related.
If two columns, one in each table, have the same name and data type.
Forge Studio detects that a search condition (e.g. the WHERE clause) is actually a join condition.

sql, define Separate relation to target table or get by joins

We're working on a CMS project with EF and MVC. We've Recently encountered a problem,
Please consider these tables:
Applications
Entities
ProductsCategories
Products
Relations are in this order:
Applications=>Entities=>ProductCategories=>Products
When we select a product by it's Id, always we should check if requested ProductsId is
just for a specific application stored in Applications table, These is for preventing load other applications products,
what is the best way to get a product for specific application id, We have two choice:
Instead of define a relation between products and applications we can do joins with productsCategories,entities, and applications to find it
=> when we want to get products we don't want to know about entities or other tables that we should join it to access applications
we can define a separate relation between products and applications and get it by simple select query
which of these is the best way and why?
Manish first thanks for your comment,Then please consider this that some of our tables does not have any relation with Entities for these tables we should define a relation with Entites to access Applications or define a separate as relation as mentioned above,For these tables we just define a relation and does not have extra work,except performance issue.still some of other tables has relations with entites so for this one defining a separat relation has extra work,
At last please consider this,in fact all of tables should access 'Entities' some by separate relation and others can access from there parents
actually for relation between products and entities we didn't define a separate relation because it doesn't has performance issue,But for relation between products and entities we should consider performance issue because in every request we should access Applications to check request Id is for current Application
So what is your idea?
Let's look at your options
Instead of defining a relationship, you can join the three tables to get the correct set of products: In this case, you won't have to make any database changes and anyway, you won't be fetching all the joined tables data, you would fetch only that data, which you have specified in your Linq Select List. But then, 3-tables join can be a little performance degrading when the number of rows will be very high at some point of time
You can define a separate relationship between the two said tables: In this case you would have to change your database structure, that would mean, making changes in your Entity and Entity Model, and lot of testing. No doubt, it will mean simple code, ease of usage which is always welcome.
So you see, there is no clear answer, ultimately it depends on you and your code environment what you want to go with, as for me, I would go for creating a separate relationship between the Application and Product entity, cause that would cause a cleaner code with a little less effort. Besides as they say, "Code around your data-structure, and not the otherway around"

ZF2 Mapping ResultSet of a Join-Statement into different Objects

when it comes down to increasing performance, reducing the amount of single SQL-Queries is one part of that.
Now let's assume a very basic example: i have a blog-table and a user-table. Each blog is referencing to a user by a given primary key.
A statement could be like
SELECT blog.title, blog.text, user.name FROM blog, user INNER JOIN on blog.user_id = user.id
Now my Blog-object i would like to have a $user-property which is a User-object
My Question: Are there inbuilt features within ZF2 to handle such a case? Or would i be needed to either manually map each field of the result into my objects?
Thanks in advance
No, there are no inbuilt features with ZF2 to do this - you should consider Doctrine 2 or Propel if you want that.
With Zend\Db however, you could write such SQL statements within your mapper class and then use an ArraySerializable hydrator to populate the blog entity. The blog entity's populate() could then choose to create a user object with the user data that is passed to it.

Yii: combination of CDbCommand and ActiveRecord queries in one Controller/Action

I was wondering if it is a good (acceptable) practice to combine those to ways of retrieving/updating database data?
For example, in my database I have two tables (Books and Users) and one "many-to-many" table Books_Users. When a user rates a book, the Books_Users table should be updated (a new record with a book_id and a user_id should be whether inserted or deleted).
I googled ways of doing it using AR methods only, but I haven't found any good solution. I ended up using CDbCommand execute() and very simple SQL-query like INSERT INTO books_users(book_id, user_id) VALUES(:bid , :uid); in a BookController action.
The point is that all my models extend CActiveRecord, and I use AR methods all the way.
So here is the question: is that kind of blending of different approaches could be used without remorse, or I should get rid of it immediately and write the code in some "proper way"?
Yii does support Many_TO_Many relations (to some degree) and this support has been improving through the 1.1.x releases http://www.yiiframework.com/doc/guide/database.arr.
Generally i don't think you will have to use CDbCommand & get dirty with SQL, you shouldn't face any problems doing it with AR specially the retrieval part, However, Insertion (Create/Update) Could be a problem (not a huge one though) since it can be solved with some triggers either on database level (database triggers) or App level (Model afterCreate() & afterUpdate()) to automate populating/updating the middle table (pivot) records.
Another (cleaner) way would be to use this extension: http://www.yiiframework.com/extension/cadvancedarbehavior/ which should do the job for you.
Last thing: take a look at this question and this one for related inquires.

Some guidance if possible? Cloning records

Very new to RoR and am working on a music app where a release can have many products. Until now I've been working away with a master 'release' level, with 'product' variant levels and 'track' levels below that.
I'm now thinking this might not be the optimal approach and am now considering a much simpler single table approach where I can clone entries to create the product variants. (My initial approach presents some serious issues in terms of importing the catalog of almost 10,000 lines currently stored in a single excel table).
In my head, the requirements would be as follows:
Create Record (this is the easy bit)
Create a clone of any record (and it's tracklisting) minus unique fields such as Cat_No/Barcode and concurrently create an association somewhere so variants can be combined in release views, admin sales reports etc.
Ability to update certain common fields like artist, title, description (to avoid having to edit each clone)
Ability to update / override certain cloned fields that in most cases will be the same, but may occasionally differ; release date for example.
Any guidance offered would be MASSIVELY appreciated.
Thanks in advance,
Ryan
I think that this functionality should be implemented in the model that is to be cloned and the logic you describe should be applied internally. I didn't understand what you meant by concurrently creating associations somewhere so variants can be combined in release views...., so I didn't answer that.
For instance:
def clone(new_attributes = {})
source_attributes = self.attributes
source_attributes.delete :cat_no #unique attributes
source_attributes.delete :barcode
merged_attributes = source_attributes.merge new_attributes
MyModel.new(merged_attributes);
end
def clone!(new_attributes = {})
copy = self.clone(new_attributes)
copy.save!
copy.reload
copy
end