Django ManyToMany Field in Both Tables - mysql

The Django docs say you can put a many to many field in either side's model, but not both. Example showing Pizzas and Toppings says it's more "normal" to think of the toppings on a pizza than think of which pizzas a topping is on, so put the field in the pizza model. OK...
However, in my application which tracks permissions and groups, this is not necessarily true. The application has a many-to-many in the permissions table showing which groups have that permission. It also seems like you should be able to look at a group and see what permissions it has. This would theoretically use the same join table.
Couldn't I add a many-to-many-through field in the groups model and specify the existing permission_group join table? Would this cause problems, as it directly violates the recommendation in the ManyToMany documentation?
Thanks...

I can't really see the reason for it. It doesn't matter which end of an electrified wire you touch - the end result is the same. What happens on the database level is exactly the same with no regard to where you add the field in Django. You can still do reverse lookups from either side (check out documentation about related_name setting, it's handy) so you can get both
a) all persons with some specific permissions
b) all permissions that a user has
If you try what you propose, you will end up with two parallel M2M fields if Django allows that - and I imagine it does, but that doesn't make any sense at all. It's like talking to the same person over two phones at the same time - why would you do that? Don't.
And as Patrick mentioned, Django has a comprehensive permissions system so you might just want to check that out and maybe it will suit your needs without any effort on your part at all.

You're making a distinction where there is none. The point of a many-to-many is that it is automatically accessible from either side of the relationship; Django does that for you. The point the docs were making was that the difference is a semantic one only; in the case they mention, toppings belong to pizzas. But even doing it that way, you can still access the pizzas from each topping.

Related

MS access multiple relationships between two tables

We had an MS Access guru at our company who left for another position. Before she left she gave me a quick introduction on how to create queries from a sql server. I am really struggling with this and as I have no one to turn to at our company I was hoping you guys could help.
Hope you can help!
Thanks!
Well, keep in mind that when you build a query, it DOES NOT necessary mean that a enforced relationship exists here. (it might).
Further more, if you imported the tables, then again its doubtful that relations are defined in Access unless you use the relationships window to "enforce" such relationships.
However, when building a query? We will often join on two fields. When you build a query in the query builder, you are free to "make up" any kind of join you want.
Say I was given two different spreadsheets. One had some people, and another had a list of hotels.
Ok, so say we want to generate a list of all people in the same city as the hotels.
You might join between table "People" and say Hotels with city.
however, WHAT happens if there is more then one state with the same City name?
Well, then just join on City AND State!!!
So you get this:
So I not have some related tables here. I just feel like and want to, and need to join the two tables of data.
As such, we never cared or setup or "had" some relationship defined, but all we care about is creating and building a working query.
So, don't confuse the simple act of building some query with that of having setup a corrrect relatonships between tables.
For a working application? Yes, you most certainly will setup relatonships.
So, if you setup relatonships correctly, then you not be able to say add a customer "invoice" reocrd without FIRST having a customer record. You don't have to do this, but it is a very good idea for a working applicaton.
However, when dealing with imported data? You often may not have an pre-defined relationships.
Now, of course in "most" cases, a query that involves multiple tables will in near all cases "follow" what you defined as relationships in the relationships window but it not necessary a requirement at all.
As noted, when building a working application? Then yes, of course you want to setup the relatonships BEFORE you start adding data.
But for general data processing, and creating queries against say different tables of data you are slicing and dicing and working with?
You are free to cook up and draw lines between the tables in the query builder, and as such, often such quires will have zero to do with the relationships you defined, or in fact even when you don't have any relationships defined at all.
That above People and the list of hotels is a great example. I mean, it rather cool that I simple joined on both City and State, and did not have to write one line of data processing code for my desired results
(a list of people in cities that live in the same city as my hotel list).
So don't confuse what we call "referential integrity" and defined relationships. We define these relationships so it becomes impossible for you the developer to add a customer invoice without first having added the customer. And it also means that you, your code, or even a editing the tables directly will not allow this to occur.
However, when dealing with just reporting, or importing data to work on? Well, then often we will not have any relationships defined, but that sure does not stop us from firing up the query builder and drawing join lines between tables.
Between two given Tables you can have one relationship involving two (of more) fields or two (or more) relationships each involving one field. Both cases are possible and have different implications.
The first case, as the first commenter pointed out, is typically used when you have a compound key in the master Table of the relationship.
The second case is typically used when you have two candidate keys in the master table, each of which is used as a master field in each of the two independent relationships.
In Ms-access the case of two independent relationships may be identified because it implies two table-boxes for the same table in the relationships pane.

How do I restrict certain values in column 2 with the same value in column 1 in SQL?

consider the following ERD for a MySQL database:
the table roles contains all kinds of (website-specific) roles users that are logged in could have. As you can see from the ERD: members can have multiple roles, and roles can have multiple members assigned to them.
The table members is dynamic, new members with custom roles can be made at any time, but the roles table is not. The current set-up of roles is final.
The records inside the roles table look like this:
id rolename
1 captain
2 cabin boy
3 buccaneer
4 parrot caretaker
5 cook
Now for the problem: I want members to have certain roles assigned to them, but certain combinations of roles cannot be chosen. For example, a captain can not also be a cabin boy, but he can also be a parrot caretaker. A cook can also be a cabin boy, but not a parrot caretaker.
I have done some research on Google regarding this topic, but I seem to fail in finding the right keywords to actually find usable information to solve this problem. All I seem to find are references and tutorials on how the SQL CHECK works, but not quite THAT in-depth.
Is there a way for me to use MySQL constraints to restrict some combinations from happening? If not, might this problem be solved using triggers or functions? I am generally looking for the most efficient solution to this, it does not necessarily have to be on the database side.
This depends on a few things..
Do you want the database to handle this logic or are you happy to have it at the application level?
If you want the database to handle it, you are probably going to want a trigger.. mysql parses a CHECK constraint but doesn't enforce it.
Either way you'll probably want to store the allowed combinations somewhere.
For simple cases I'd go for either a black-list or a white-list of other roles for each role depending on numbers. You can store this easily in another table.
Another option is a pre-requisite table, for example to be an admiral you must also be a captain.

Is there an elegant way to update model relations?

I am using Ruby on Rails, however am interested in a general solution as well. Lets say I have a model users, a model cuisines, and a relational table connecting the two allowing a user to have a list of 'favorite cuisines'. The user is presented with a list of all the cuisines and can check or uncheck them individually. For example lets say Alice starts off liking American, Indian, and Chinese food. She then unchecks Chinese and adds in Thai and hits save. Whats the best way to go about updating the relational table?
I have three solutions, but since this operation seems so common I was hoping for a more elegant solution. If there isn't, what is the standard way to do this?
keep a set of added and a set of removed, and make sure they have no overlap
drop all of the users favorite foods and insert the selected ones
make ajax calls to update each individual add and remove
use the association_ids approach. Instead of looking for a list cuisines and then assigning them to the user, just get a list of their ids and assign it to user.cuisine_ids. Saving the record will generate the association records for you. Since you're using checkboxes, be wary of the scenario where a user unchecks everything and then saves. What usually happens is no change is saved keeping the old selected cuisines selected. This can be easily fixed by adding a nil hidden value with the same name as the checkboxes.

Why would a Microsoft Access form create records for one query but not another?

I have an Access database. Let's pretend it's for a pet store.
There's a table for animals.
Animals (animal_id, birth_date, price)
And then specific tables for the different types of animals we sell.
Dogs (animal_id, bark_volume)
Cats (animal_id, collar_size, shedding_rate)
Fish (animal_id)
Fish aren't interesting so they don't have any special fields. The Fish table just exists so you know which records in the Animals table are fish.
Now, I have a general purpose form for adding animals to the pet store. Before you get the form, you first have to say what kind of animal you're adding. Based on that, the form shows/hides fields, changes its recordsource, and binds the fields to the appropriate data columns. The form pulls its data from the queries DogInfo, CatInfo, and FishInfo.
Now, when you enter a dog or a cat, everything is fine. A record is added to both Animals and either Dogs or Cats.
However, when you enter a Fish, all you get is an Animal, no Fish.
What could be causing this? Is it somehow caused by the lack of other columns on the Fish table?
(Let's leave aside the fact that updating tables with a select query makes no sense at all. I didn't expect Access to let me do it at all in the first place, but Access's motto seems to be "Make the wrong thing easy to do and the right thing awkward to do." The database is relatively simple and infrequently used, though, and it's at least 100 times better than it was before I started working on it, so I'm not really too worried about this issue as long as I can make it work.)
"Is it somehow caused by the lack of other columns on the Fish table?"
Yes - when you enter data on child records (Dogs and Cats) Access will automatically fill in the parent ID (animal_id)
Since there is no data entry for the fish record it does not get created. You have to do that in code. Not sure how your form and data source is setup but you would do something like this on one of the form events:
Fish![animal_id] = Animal![animal_id]
Edit
In your FishInfo query you must give the Fish.[animal_id] an alias - you can't have two fields with the same name - call it Fish_animal_id
Then in the Form_BeforeUpdate event put this:
Me.Fish_animal_id = Me.animal_id
Have you thought about configuring relationships on the different tables? Given the design above, I would start by adding an identifying column to the specific-animal tables, and setting it as the primary key. E.g.:
Dogs(DOG_ID, animal_id, bark_volume)
Cats(CAT_ID, animal_id, collar_size, shedding_rate)
etc. In the relationships view, you'd then define a one-to-many (one-to-one?) relationship from Animals.ANIMAL_ID to Dogs.animal_id. You could then hook up the Animals table to a combo/listbox control on your form to select a record from that table. I think if you configure the control correctly, you can even create new records from that control (or you could use a subform).
Do you not have an separate IDs for the Dogs/Cats/Fish tables? Assuming the only difference is the number of columns, I'd be curious if that suddenly fixed it.
Bad design aside, did you set up a relationship between the various tables? And did you set the tables to enforce referential integrity?

Keeping Drop-downs DRY in a web app

I'm writing a CMS for various forms and such, and I find I'm creating a lot of drop-downs. I don't really feel like mucking up my database with tons of random key/string value tables for simple drop-downs with 2-4 options that change very infrequently. What do you do to manage this in a responsible way?
This is language-agnostic, but I'm working in Rails, if anyone has specific advice.
We put everything into a single LookUp table in the database, with a column that mapped to an enum that described which lookup it was for (title, country, etc.).
This enabled us to add the flexibility of an "Other, please specify" option in lookup dropdowns. We made a control that encapsulated this, with a property to turn this behaviour on or off on a case-by-case basis.
If the end user picked "Other, please specify", a textbox would appear for them to enter their own value. This would be added to the lookup table, but flagged as an ad hoc item.
The table contained a flag denoting the status of each lookup value: Active, Inactive, AdHoc. Only Active ones would appear in the dropdown; AdHoc ones were those created via the "Other, please specify" option.
An admin page showed the frequency of usage of the AdHoc values, allowing the administrators of the site to promote common popular values into general usage (i.e. changing their Status flag to Active).
This may well be overkill for your app, but it worked really well for ours: the app was basically almost entirely CRUD operations on very business-specific data. We had dozens of lookups throughout the site that the customer wanted to be able to maintain themselves. This gave them total flexibility with no intervention from us.
You cold have one single dropdown table with an extra column to say what the drop down is for... limit the results with a where clause...
At my current position, we implemented a LookupCode table that contains a CodeGroup,Code, and Meaning column, as well as some others (like active). That way you have a single table that contains all of your lookup values are in a single location and you can do some quick lookups to bind to your dropdown lists.