Well, I do my first steps with Django and Django REST framework. The problem I face is that all examples throughout the whole Internet are based on hard-coded models. But the whole concept of models frustrates me a little bit, because I'm used to deal with different data which comes from numerous sources (various relational databases and nosql - all that stuff). So, I do not want to stick to a particular model with a fixed number of predefined fields, but I want to specify them just at the moment when a user goes to a particular page of my app.
Let's say I have a table or a collection in one of my databases, which stores information about users - it has any kinds of fields (not just email, name and likewise - all those fields as in all those examples throughout the web). So when a user goes to /users/ I connect to my datebase, get my table, set my cursor and populate my resultant dictionary with all rows and all fields I need. And REST API does all the rest.
So, I need a "first-step" example wich starts from data, not from a model: you have a table "items" in your favorite database, when a user goes to /items/, he or she gets all data from that table. To make such simplistic api, you should do this and this... I need this kind of example.
I think the key is to use the models differently. If you use onetomany or foreignkey references in your model construction you can more dynamically link different types of data together, then access that from the parent object.
For example, for your user, you could create a basic user model and reference that in many other models such as interests, occupation, and have those models store very dynamic data.
When you have the root user model object, you can access it's foreign key objects by either iterating through the dictionary of fields returned by the object or accessing the foreign key references directly with model.reference_set.all()
Related
I'm currently working on a project where I handle both public and private information, both stored as different models in a common database.
I would like to split this database in two, one with the private model objects and another one with the public ones.
The thing is, both this models have a ForeignKey relationship with each other, and I've found conflicting answers over the internet about if this relationships can work even if the models are in two different databases.
So, is this possible? Is there a better approach for doing this?
Just to clarify why I want to do this, I want the project to be open source, therefore the public database should be public, but the sensitive information (users and passwords) should be kept private.
From Django docs:
Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.
This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.
For possible solutions check out this discussion: https://stackoverflow.com/a/32078727/14209813
I'm creating API with Django rest framework. I've one table which will be used as types for the products. Another table which will map that types with the product. consider it as producttypesmapping table. So, I'm creating product type update endpoint. which will only update the producttypesmapping.
The issue is I've used ChoiceField() in the serializer. So I need the tuple of tuples variable to prevent from storing unwanted values. which will be initialized in util.py and to make it dynamic it loads directly by querying the producttypes table. So, I only have to query the data only once.
TAG_CHOICES_TYPE_ONE = []
tags = ProductTypes.objects.filter(tag_type_id=1).values('id', 'value')
for index, item in enumerate(tags):
TAG_CHOICES_TYPE_ONE.append((item["id"], item["value"]))
TAG_CHOICES_TYPE_ONE = tuple(TAG_CHOICES_TYPE_ONE)
But the problem is utils.py executed before the even the producttypes initialized with any data.
First of all, unless you want to attach some additional data about the mapping, your mapping model shouldn't be necessary. Simply use a ForeignKey or a ManyToManyField.
Then, you should consider using a PrimaryKeyRelatedField instead of a ChoiceField. This field takes a queryset as an argument, which will help you limit your choices. If you chose a ChoiceField to be able to get a nice display in the browsable API, you can achieve the same by creating a string representation for your model.
I created website-app for myself and it become really useful and many peoples wont also use it. But user management was not scheduled in application architecture. Is there any way to easy add user registration so each user would have his own google database tables but with same name?
example of one "table":
class Settings(db.Model):
email = db.StringProperty()
link = db.LinkProperty()
rating = db.StringProperty()
How can I separate data from this "table" between different users? I search for some kind of wrapper so I don't need to change current architecture.
You have to remember there is no concept of tables with the datastore so you can't have a separate set of tables for each user as such.
You have a few choices, the two I would investigate are
create a separate app with the existing code base and each user runs their own site. You may not need to do any code changes at all
If you want complete separation of data for each user in a single app then look at namespaces (thats how multi-tenancy is normally implemented.)
However you haven't really provided a clear definition of how you want to separate the users etc.. so there a probably other approaches you can take.
Short of having a copy of the database for each user; you'll have to implement some code changes.
The easiest one you can do is add a foreign key to your data tables that points to your user table; then you filter all records based on this foreign key.
Once you have that change, you can write a view decorator that will automatically filter the records for you.
I'm a novice in Django (but an experienced developer), and I'm starting to build my first Django project.
The project is really simple: a website where people can join events. An administrator sets an sports event, chooses the date, the kind of event (running, tennis match, bycicle ride), etc, and users can join it.
My problem is that the events can have very different data inside, depending on his category. For example, if it's a two-people team tennis match, an users should enter his name and his teammate name, their team name, etc. If the event is a bycicle ride, he can choose if he wants the difficult or the easy route, etc.
I know I can create a big model with all the attributes for every kind of event, but this is a really ugly design... There should be a common table for all registrations, with a link to the event and the basic and common data (name, address, phone, email, etc), but I don't know how to handle the specific data for each sport/event category... Any idea about how to organize this in Django models? Maybe adding a simple (key, inscription_id, type, value) table? And then, how can I render the form?
I believe what you suggested is called Entity-attribute-value model
http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model
I think there could be a good argument for keeping all data belonging to your events defined inside of a model instead of through a related generic EAV table.
To do this you could use one of django's polymorphic libraries. I have used django-model-utils' InheritanceManager in production. There are quite a few libraries including django-polymorphic.
Taking an inhertance based approach you might define a single Event model or Sport model. A sport might have a name, league, etc. All Events might have a start date and end date and sport.
Using this approach you can defined foriegn keys from your registrations to the base Event class and use djangos built in ORM to select all events or registrations of certain types, without having the additional application logic/object inspection/ property inspection of taking an EAV approach!
You can store all additional data in Text field using JSON object or other serializer.
Take look at django-jsonfield
I have two tables with a many-to-many relationship between them. One table holds types of properties, the other holds regions.
For the sake of simplicity let's say it goes something like this:
_property_
id
name
description
_region_
id
name
_property-region_
id
property.id
region.id
I want to build a form to create new properties, and I want this form to contain a multi-select option allowing the user to specify which region/s the property is available in.
I understand that I can create a multi-select form using list:reference without actually creating a junction table, but I would be interested in learning how to do this without de-normalising the database.
its not denoramalising?
each region can have many properties and relation is held by region...
on the query level you just ask for regions which hold the id of the property... (either way you have to query db for that even if you have junction/through table)
If you have specific info about relation, you have to process that logic yourself. Aint that hard,
create two forms validate property info and the record will be in database thus you posess the id. Then just add that id as one part of relation and all the selected items as other.