I am new to Django plotform. I am trying to write a program which basically accepts a post method. The content of incoming data is storename, bookname, bookserial. That part is already implemented and works well. When I post the content such as storename=John's shopping center, bookname=Love is beatiful, bookserial=123. It creates a table and save those things into a table. But, the thing is that I want to create not just only one table for each store. Because, I can have multiple storename and each store should have its own table. When I post the storename on the fly ,it should check storename and then if it's table is created already, the bookname and bookserial should be inserted its table. If not, a new table should be created and then the incoming data is inserted the new table. The new table name should be storename as well.So, as I said, I only need to learn how to create new tables on the fly part. Could you please help me how to do that, any comments and ideas is appreciated....
An example to make it clear,
Table-1=John's shopping center
bookname=Love is beatiful
bookserial=123
Table-2= John's shopping center-2
bookname=Time is important
bookserial=456
So, the model is same for each shopping center but each of sopping center is a different table with the name of shopping center.
In the traditional sense, it is not possible to dynamically create concrete tables on the fly in django. Models have to be registered as part of the application startup, so that the ORM can properly manage all the relations. Consider what would happen if you defined a new model that set up constraints or backrefs to other models. Those other models, being classes, have already been set up and are in memory. They can no longer go through their metaclass step to wire new relations. You could easily break things.
Your options are limited to either a solution involving a few tables that can dynamicaly describe different entities, or to use a nosql backend that does not care about schemas and will let you store anything at any time.
See this question and answer for details: Django dynamic model fields
The only way to have a concrete table on the fly is if you have the django app restart itself completely in response.
Related
newly working with GraphQl and wondering is it possible to filter a set in a query? I'm still new to database design as well so could be an issue there.
So I run the below query, managerGwPicks has a field player with is a player object containig their name etc.
This player object contains a set of all the weeks they have played which is a separate table in my database.
So as can be seen in the above image when I display the set it shows all the gameweek data whereas ideally I would like it filtered by the gameweek:21 parameter passed to the managerGwPicks query.
I'm not sure it should be possible as there is no direct link between the managerGwPicks and playergwstats tables but I'd like to be sure that my thinking is correct.
My solution for my front end would be to have two queries, one similar to what I have getting the player information and a second query using the player id and gameweek to query playergwstats to get the player stats for the individual week. Does this sound like a reasonable approach?
It's preferable to avoid query patterns where you have to do multiple back-and-forths between the client and the server. If you can imagine making the link on the client then you can do it directly on the server. If you can go from a managerId and gameweek to a list of players and you can go from players to playergwstats then you can create a join that goes from your two parameters to all the relevant players.
I've covered patterns like this in a series of posts on GraphQL for SQL Developers - look at the join that's used to go from a booking reference to a series of tickets and flights.
I have 4 tables in my database. The image below shows the rows and columns with the name of the table enclosed in a red box. 4 tables total. Am I going about the relationship design correctly? This is a test project and I am strongly assuming that I will use a JOIN to get the entire set of data on one table. I want to start this very correctly.
A beginner question but is it normal that the publisher table, for example, has 4 rows with Nintendo?
I am using Django 1.7 along with PostgreSQL 9.3. I aim to keep simple with room to grow.
Basically you've got the relations back-to-front here...
You have game_id (i.e. a ForeignKey relation) on each of publisher, developer and platform models... but that means each of those entities can only be related to a single game. I'm pretty sure that's not what you want.
You need it the other way around... instead put three foreign keys onto the game model, one each for publisher, developer and platform.
A ForeignKey is what's called a many-to-one relation. In this example I think what you want is for 'many' games to be related to 'one' publisher. Same for developer and platform.
is it normal that the publisher table, for example, has 4 rows with Nintendo?
No, that's is an example of why you have it backwards. You should only have a single row for each publisher.
yes you are correct in saying that something is wrong.
First of all those screen shots are hard to follow, for this simple example they could work but that is not the right tool, pick up pen and paper and sketch some relational diagrams and think about what are the entities involved in the schema and what are their relations, for example you know you have publishers, and they can publish games, so in this restricted example you have 2 entities, game and publisher, and a relation publish among them (in this case you can place a fk on game if you have a single publisher for a game, or create an intermediary relation for a many to many case). The same point can be made for platform and games, why are you placing an fk to game there, what will happen if the game with id 2 will be published for nintendo 64 ? You are making the exact same mistake in all the entities.
Pick up any book about database design basics, maybe it will help in reasoning about your context and future problems.
I am using django and have three objects: Customer, Location and Department. Each has a related Setting object.
Is it better form to create a single table with optional/null foreign keys?
Or to create a different setting object/table for each of the 3 entities?
There are a few options
Create a separate Settings table and have a nullable ForeignKey from all of your objects to the Settings table. If you choose this option, you should create an abstract base class that has a ForeignKey to the Settings table and inherit from that abstract base class. That way you don't have to add the ForeignKey every time you create a new model.
Create a separate Settings table and use GenericForeignKeys from the Settings table to reference your object (Customer, Location, and Department). This has the advantage of not having an extra column in all of your tables that need settings. However, you can't do DB joins with GenericForeignKeys via the Django ORM's normal API. You'd have to use raw sql. Also, select_related doesn't work on GenericForeignKeys so you'd have to use prefetch_related instead.
Store the settings in a column in the database. You should interact with the data in some format (I like JSON) and then serialize it to a string to store in the DB. Then to read the settings, you could deserialize the string back into JSON and interact with it. With this method, you wouldn't need to join with another table to get settings, and wouldn't need to run migrations every time you added new settings. You also wouldn't need a separate Settings table. However, constructing a query to find objects with certain settings would be a pain the query would probably be slow as well.
Each option has its pros and cons; so, pick your poison ;)
I'm currently implementing a solution using django admin, it allows users to define in the db a product, and then custom attributes and details, more details may be aggregated by a common attribute, this allows me to query with ajax a custom view that returns some JSON data to build automagically the form fields that I need directly in the same formset view (manipulating the DOM).
The current DB design follows this schema:
Catalog(name, description, photo)
Product(rel_catalog, name, base_price, photo, manufacturer_email)
ProductDetail(rel_product, rel_attribute, percentage_price, fixed_price)
ProductAttribute(rel_product, name, description)
As you may see I have a catalog, where there can be more products, a lot of details per product, aggregated by attributes. Then I simple show by default the Catalog, then the select with all available products for that catalog, then, choosing the right Product, I obtain the complete form (each row has a label with ProductAttribute.name and a select with related ProductDetail).
All works pretty dam good, but I also need to store this references in the DB when someone completes the form (making an order with choosen products). This forms are displayed as StackedInline (the ModelAdmin is for the Order).
I don't know how many options there may be per product so I was thinking to use this design to track orders:
Order(customer, status, notes, tot_price, inserted_by)
OrderItem(rel_order, catalog, product, unit_price)
But I don't know how to store the dynamic added inputs...
I was thiking to implement OrderItemProperty(rel_orderitem, rel_productdetail, rel_productattribute) to store each single input... but how do I loop over this unknown fields?
Maybe do you suggest a better design?
If you need more code just ask for it and I'll reply with a pastebin link.
Thankyou.
Finally I got a working solution,
I've created a custom view, overriding the default "add/" view, this way I can customize whatever I want to and I can read the POST data handling each validation, putting then the data in the right model.
I have an app that allows a user to create an estimate for a project. The estimate has the basic client information (name, address, phone number, etc.) and a custom Primary Key value that I generate. Now, I also have two other models for listing estimated products and labour needed for the job. These two models are linked to the "main" estimate model with a Foreign Key. For these two models I was going to use inline formsets since they, by default, link to another record via a foreign key.
I'm wondering if it is possible to create the main estimate (the basic data) record at the same time as the two inline forms? It seems like it wouldn't work (well, I'm having trouble making it work) since the foreign key that the two inline formsets are linked to doesn't exist yet because it is also just being created.
Would it be better to make this a two step process: Step 1) Create & save basic data (thereby creating the primary key that can be linked to) Step 2) Add product and labour records linking them by the foreign key of the main record. It just seems that this would be a poor UI design (having two steps).
Thoughts?
Thanks!
I'm wondering if it is possible to create the main estimate (the basic data) record at the same time as the two inline forms?
This is, in fact, the way the admin (django.contrib.admin) does it for an inline form.
If you don't feel like diving into that code, you could try to use transactions to bundle all the database changes together, so you can roll them all back if needed. This assumes your back-end database supports transactions, of course.