Now I'm working one url mapping. Let's say I have three classes, company, user, and store, and my goal is that their urls will be in the same hierarchy. Since they are the same hierarchy in urls, I have to create a class url_mapping to ensure there is no duplicate name. Let's me give a more concrete problem I have.
Class Company(models.Model):
company_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class User(models.Model):
user_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class store(models.Model):
store_name = models.CharField(max_length=30)
url_mapping = models.OneToOneField(URL_mapping)
Class URL_mapping(models.Model):
url = models.CharField(max_length=30)
Now, when a visitor access to my site with certain url, I'll match the url in URL_mapping class, and then do the reverse lookup and see which type of url between company, user, and store it is.
Since User, Store, and Company have different view function, is it possible that we can quickly re-directly to the corresponding view function quickly using reverse lookup? Or should I add another field in URL_mapping saying that which url type it is?
The example is
http://www.example.com/levis -> will handle by brand_views
http://www.example.com/david -> will handle by user_views
http://www.example.com/mancy -> will handle by store_views
In database, we will have
url_mapping
id:1, name:levis
id:2, name:david
id:3, name:mancy
user
id:1, name:david, url_mapping:2
brand
id:1, name:levis, url_mapping:1
store
id:1, name: mancy, url_mapping:3
Where url_mapping is oneToOneField.
Don't know how to quickly look up from url_mapping class now.
Thank you.
I understand your question as "I have a URL, and I want to go to the corresponding Store, company or the User".
You can do that using
URL_mapping.objects.get(url).user
URL_mapping.objects.get(url).store
URL_mapping.objects.get(url).company
Clearly 2 of these will give you an error and you wouldn't know which it maps to.
Seems to me like, for what you are really looking for here, you should really use Generic Foreign Keys
So, then you will be able to do:
URL_mapping.objects.get(url)
which will have the corresponding User, Company or the Store model.
I would use a SlugField in each model (Company, User, Store) as their identifier.
theoretically, you do not need any URL mapping tables at all, in the view that handles the requests, extract the last part of the url, which is a slug identifying a Company, or a User, or a Store, and search Company, then User, and then Store models for the given slug. Stop when you find the object.
to improve speed, you can create an auxiliary model like you did and use GenericForeignKey relation as Lakshman Prasad suggested. In this auxiliary model, again, I would use a SlugField for an identifier. And if you use that, you do not need slugs in your main models.
I personally think this is a bad design. First, I doubt that these URLs are REST-ful. Second, for this to work, the slugs in your main models have to be unique across these three models, which can be ensured by only an external mechanism, you cannot use a UNIQUE constraint here. Your URL_mapping model is simply one such mechanism. It basically stores your slugs for the three models outside the models and, if you add the UNIQUE constraint to the SlugField in URL_mapping, makes sure the slugs are unique across your main models.
Related
I am trying to build a Django website where the user is able to create custom objects known as items. Each item needs to be able to have certain properties that are stored in the database. For example an item would need properties such as
Serial Number,
Description,
Manufacture Date
However I want the user to be able to specify these fields similar to what Microsoft dynamics allows . For example a user should be able to specify they want a text field with the name Model Number, associated with a specific item type and from then on they can store those properties in the database.
I am not sure the best approach to do this because a standard database model, you already have all the fields defined for a specific table, however this essentially means i have to find a way to have user defined tables.
Does anyone know a good approach to handle this problem, at the end of the day I want to store items with custom properties as defined by the user in a database.
thanks
There are multiple ways you can go.
In non-relational databases you don't need to define all the fields for a collections ( analogous to a table of RDBMS).
But if you want to use SQL with Django, then you can define a Property Model.
class Property(models.Model):
name = CharField()
value = CharField()
item = models.ForeignKey(Item, on_delete=models.CASCADE)
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
You can render a FormSet of Property form. To add extra empty forms on the fly, render dynamic formsets.
I have gone through the question, best way to implement privacy on each field in model django and Its answers doesn't seem solve my problem so I am asking some what related question here,
well, I have a User model. I want the user to make possible to control the privacy of each and every field of their profile (may be gender, education, interests etc . ..).
The privacy options must not to be limited to just private or public, but as descriptive as
public
friends
only me
friend List 1 (User.friendlist.one)
friend List 2 (User.friendlist.two)
friend List 3 (User.friendlist.three)
another infinte lists that user may create.
I also don't want these privacy options to be saved on another model, but the same so that with one query I could get the user object along with the privacy options.
so If I have the UserModel,
class User(models.Model):
name = models.CharField()
email = models.EmailField()
phone = models.CharField()
How do I setup a privacy setting here? I am using postgres, can I map a JSON field or Hstore even an ArrayField?
what is the best solution that people used to do with Django with same problem?
update:
I have n model fields. What I really want is to store the privacy settings of each instance on itself or some other convenient way.
I have worked on my issue, tried solutions with permissions and other relations. I have a Relationship Model and all other relationship lists are derived from the Relationship model, so I don't want to maintain a separate list of Relationships.
So my pick was to go with a Postgres JSONField or HStoreField. Since Django has good support for postgres freatures, I found these points pro for the choice I made.
JSON/HashStore can be queried with Django ORM.
The configurations are plain JSON/HashStore which are easy to edit and maintain than permissions and relations.
I found database query time taken are larger with permissions than with JSON/HStore. (hits are higher with permissions)
Adding and validating permissions per field are complex than adding/validating JSON.
At some point in future if comes a more simple or hassle free solution, I can migrate to it having whole configuration at a single field.
So My choice was to go with a configuration model.
class UserConfiguration(models.Model):
user = # link to the user model
configuration = #either an HStore of JSONFeild
Then wrote a validator to make sure configuration data model is not messed up while saving and updating. I grouped up the fields to minimize the validation fields. Then wrote a simple parser that takes the users and finds the relationship between them, then maps with the configuration to return the allowed field data (logged at 2-4ms in an unoptimized implementation, which is enough for now). (With permission's I would need a separate list of friends to be maintained and should update all the group permissions on updation of privacy configuration, then I still have to validate the permissions and process it, which may take lesser time than this, but for the cost of complex system).
I think this method is scalable as well, as most of the processing is done in Python and database calls are cut down to the least as possible.
Update
I have skinned down database queries further. In the previous implementation the relations between users where iterated, which timed around 1-2ms, changing this implementation to .value_list('relations', flat=True) cut down the query time to 400-520µs.
I also don't want these privacy options to be saved on another model, but the same so that with one query I could get the user object along with the privacy options.
I would advice you to decouple the privacy objects from the UserModel, to not mess your users data together with those options. To minimize the amount of database queries, use djangos select_related and prefetch_related.
The requirements you have defined IMO lead to a set of privacy related objects, which are bound to the UserModel. django.contrib.auth is a good point to start with in this case. It is build to be extendable. Read the docs on that topic.
If you expect a large amount of users and therefore also an even larger amount of groups you might want to consider writing the permissions resolved for one user in a redis based session to be able to fetch them quickly on each page load.
UPDATE:
I thought a little more about your requirements and came to the conclusion that you need per object permission as implemented in django-guardian. You should start reading their samples and code first. They build that on top of django.contrib.auth but without depending on it, which makes it also usable with custom implementations that follow the interfaces in django.contrib.auth.
What about something like this?
class EditorList(models.Model):
name = models.CharField(...)
user = models.ForeignKey(User)
editor = models.ManyToManyField(User)
class UserPermission(models.Model):
user = models.ForeignKey(User)
name = models.BooleanField(default=False)
email = models.BooleanField(default=False)
phone = models.BooleanField(default=False)
...
editor = models.ManyToManyField(User)
editor_list = models.ManyToManyField(EditorList)
If a user wants to give 'email' permissions to public, then she creates a UserPermission with editor=None and editor_list=None and email=True.
If she wants to allow user 'rivadiz' to edit her email, then she creates a UserPermission with editor='rivadiz' and email=True.
If she wants to create a list of friends that can edit her phone, then she creates and populates an EditorList called 'my_friends', then creates a UserPermission with editor_list='my_friends' and phone=True
You should then be able to query all the users that have permission to edit any field on any user.
You could define some properties in the User model for easily checking which fields are editable, given a User and an editor.
You would first need to get all the EditorLists an editor belonged to, then do something like
perms = UserPermissions.objects.filter(user=self).filter(Q(editor=editor) | Q(editor_list=editor_list))
First of all, in my opinion you should go for multiple models and for making the queries faster, as already mentioned in other answers, you can use caching or select_related or prefetch_related as per your usecase.
So here is my proposed solution:
User model
class User(models.Model):
name = models.CharField()
email = models.EmailField()
phone = models.CharField()
...
public_allowed_read_fields = ArrayField(models.IntegerField())
friends_allowed_read_fields = ArrayField(models.IntegerField())
me_allowed_read_fields = ArrayField(models.IntegerField())
friends = models.ManyToManyField(User)
part_of = models.ManyToManyField(Group, through=GroupPrivacy)
Group(friends list) model
class Group(models.Model):
name = models.CharField()
Through model
class GroupPrivacy(models.Model):
user = models.ForeignKey(User)
group = models.ForeignKey(Group)
allowed_read_fields = ArrayField(models.IntegerField())
User Model fields mapping to integers
USER_FIELDS_MAPPING = (
(1, User._meta.get_field('name')),
(2, User._meta.get_field('email')),
(3, User._meta.get_field('phone')),
...
)
HOW DOES THIS HELPS??
for each of public, friends and me, you can have a field in the User model itself as already mentioned above i.e. public_allowed_read_fields, friends_allowed_read_fields and me_allowed_read_fields respectively. Each of this field will contain a list of integers mapped to the ones inside USER_FIELDS_MAPPING(explained in detail below)
for friend_list_1, you will have group named friend_list_1. Now the point is the user wants to show or hide a specific set of fields to this friends list. That's where the through model, GroupPrivacy comes into the play. Using this through model you define a M2M relation between a user and a group with some additional properties which are unique to this relation. In this GroupPrivacy model you can see allowed_read_fields field, it is used to store an array of integers corresponding to the ones in the USER_FIELDS_MAPPING. So lets say, for group friend_list_1 and user A, the allowed_read_fields = [1,2]. Now, if you map this to USER_FIELDS_MAPPING, you will know that user A wants to show only name and email to the friends in this list. Similarly different users in friend_list_1 group will have different values in allowed_read_fields for their corresponding GroupPrivacy model instance.
This will be similar for multiple groups.
This will be much more cumbersome without a separate permissions model. The fact that you can associate a given field of an individual user's profile with more than one friend list implies a Many to Many table, and you're better off just letting Django handle that for you.
I'm thinking something more like:
class Visibility(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
field = models.CharField(max_length=32)
public = models.BooleanField(default=False)
friends = models.BooleanField(default=False)
lists = models.ManyToManyField(FriendList)
#staticmethod
def visible_profile(request_user, profile_user):
"""Get a dictionary of profile_user's profile, as
should be visible to request_user..."""
(I'll leave the details of such a method as an exercise, but it's not
too complex.)
I'll caution that the UI involved for a user to set those permissions is likely to be a challenge because of the many-to-many connection to friend lists. Not impossible, definitely, but a little tedious.
A key advantage of the M2M table here is that it'll be self-maintaining if the user or any friend list is removed -- with one exception. The idea in this scheme is that without any Visibility records, all data is private (to allow everyone to see your name, you'd add a Visibility record with user=(yourself), field="name", and public=True. Since a Visibility record where public=False, friends=False, and lists=[] is pointless, I'd check for that situation after the user edits it and remove that record entirely.
Another valid strategy is to have two special FriendList records: one for "public", and one for "all friends". This simplifies the Visibility model quite a bit at the expense of a little more code elsewhere.
I am creating model class Car and I want to have in it two references to one foreign key.
class Car(models.Model):
owner = models.ForeignKey(User)
#and here I want to have owner email (which is already set in class User)
email = owner.email
But I don't know how to make reference to field of ForeignKey already used.
I get this error:
AttributeError: type object 'User' has no attribute 'email'
Is there any way to do it?
There are two things here... the first is to find out why you want to do this. Because maybe you shouldn't.
If you just want to access the owner's email address from a Car instance you don't need to add it as a field on the Car model, you can do:
my_car = Car.objects.get(owner=me)
my_email = my_car.owner.email
This does two seperate db queries, the first to get the Car and the second to get the owning User when you access the ForeignKey.
If you want to avoid this you can use select_related:
my_car = Car.objects.select_related().get(owner=me)
my_email = my_car.owner.email
Now it's only one query, Django knows to do a join in the underlying SQL.
But, assuming you know all this and you still really want to add the owner's email to the Car model. This is called 'denormalisation' and there can be valid performance reasons for doing it.
One problem that arises is how to keep the email address in sync between the User and Car models. If you are deliberately pursuing denormalisation in your Django app I highly recommend you consider using django-denorm. It installs triggers in the SQL db and provides a nice interface for specifying denormalised fields on your model.
You should really follow django's tutorial...
You can access the user email with car_instance.owner.email.
There is no need to add existing fields to another module. You should in principle avoid repeating data. Since the email and all relevant user info exist in the user model, then the foreign key is enough to access this data in relevance to a specific car record:
car = Car.objects.first()
email = car.owner.email
You can do the same with any field of the user model.
I am in the early stages of a project using Django, Django REST Framework, and SQL. I am very new to DRF.
I have a model that tracks user info for a game service that runs different servers for regions of the world (ex. NA, EU, etc). User IDs are only unique per-region, but the users are all stored using the same model (table). I am employing unique_together = ('user_id', 'region') in my model's Meta class to ensure there are no duplicates. Please note that, as such, the PKs in the DB are not related to the user IDs.
DRF, by default, would create endpoints using the DB's PKs of Users, but I have changed that to use a system like /users/na/123 to get the object where user_id = 123 and region = 'na' (north america). A snippet for this from urls.py follows:
url(r'^users/(?P<region>.+)/$', UserList.as_view()),
url(r'^users/(?P<region>.+)/(?P<user_id>.+$)', UserDetail.as_view()),
These are generic views (generics.ListAPIView and generics.RetrieveAPIView), respectfully.
Currently, the rest of my views are ViewSets.
One of the things I model is historical match data, where users are related to by a Game model, to keep track of who participated in a match like so:
class Game(models.Model):
player_1 = models.ForeignKey(User)
player_2 = models.ForeignKey(User)
I plan on implementing a route for games like I did w/users (again, game_id is unique only per-region) so I can do /game/<region>/<game_id>.
My question is this:
How can I get hyperlinks to Users using my established /user/<region>/<user_id> routes in Game list/detail views on the API?
Presently, my GameSerializer is defined as follows:
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
exclude = ('id',)
When I change it to a HyperlinkedModelSerializer I get the following error upon visiting the Game endpoints:
Could not resolve URL for hyperlinked relationship using view name
"user-detail". You may have failed to include the related model in
your API, or incorrectly configured the lookup_field attribute on
this field.
I assume this is because my User endpoints are implemented differently than what it expects (it can't know I have abandoned the default PK indexing method and opted for a custom route a la /users/<region>/<user_id> instead of /users/<pk>, right?)
How do I approach this problem? I would be open to suggestions that are extraneous to the DRF side of things, like restructuring my DB/Django models, if it seems like the direction I want things to go is crazy (not wanting to use PKs).
After a few more days of reading and thinking about the problem differently, it looks Meta.unique_together is kind of like expressing a composite key in SQL. This lead me to this solution:
https://groups.google.com/forum/#!topic/django-rest-framework/tHmEAzSNgG4
e.g. instead of using an URL like this to identify an employee:
api/1.3/employee/5/
I use an URL like this:
api/1.3/company/23/employee/5/
I use a HyperlinkedModelSerializer to serialise this model. I
couldn't find a way of configuring a HyperlinkedIdentityField to
handle the composite key (you can only specify a single lookup_field)
so I override the url with a SerializerMethodField instead, like this:
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField('get_employee_detail_url')
def get_employee_detail_url(self, obj):
# generate the URL for the composite key
...
return composite_key_url
Still exploring my options, but this looks pretty clean.
I just came up against the same problem today. After going through the Django-Rest-Framework documentation on Generic views I came across:
lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk'. Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.
http://www.django-rest-framework.org/api-guide/generic-views
In my case I did this in my models.py
class UserDetailView(generics.RetrieveAPIView):
model = User
serializer_class = UserSerializer
lookup_field = "username"
...and works lovely now. Hope that helps.
Note: I've since asked this question again given the updates to Django's user model since version 1.5.
I'm rebuilding and making improvements to an already existing Django site and moving it over from Webfaction to Heroku, and from Amazon's SimpleDB to Heroku Postgres (though testing locally on Sqllite3 when developing). A lot of what I'm doing is moving over to use built-in Django functionality, like the Django admin, user authentication, etc.
Conceptually, the site has two kinds of users: Students and Businesses. The two types of users have completely different permissions and information stored about them. This is so much the case that in the original structure of the site, we set up the data model as follows:
Users
ID (primary_key)
Business_or_Student ('B' if business, 'S' if student)
email (unique)
password (hashed, obviously)
...
Students
ID (Foreignkey on Users)
<more information>
...
Businesses
ID (Foreignkey on Users)
<more information>
...
This worked pretty well for us, and we had the bare-bones user information in the Users table, and then any more detailed information in the Students and Businesses tables. Getting a user's full profile required something along this pseudocode:
def get_user_profile(id):
if Users(id=id).Business_or_Student = 'B':
return Businesses(id=id)
else:
return Students(id=id)
In moving over, I've found that Django's built-in User object has pretty limited functionality, and I've had to extend it with a UserProfile class I've created, and then had additional Student and Business tables. Given all of the patching I'm doing with this in the Django admin, and being relatively unfamiliar with Django models since I always did it differently, I'm not sure if this is the best way to go about it, or if I should just stick all of the information for businesses and students in the UserProfile table and just differentiate the two with different groups, or if there's even some way to do this all in the built-in User object.
Since businesses and students also have different interfaces, I'm seriously considering setting up the two as different apps within my Django project, and so separating their views, models, etc. entirely. That would look something like:
MyProject/
MyProject/ (project folder, Django 1.4)
mainsite/
students/
businesses/
One of my biggest concerns is with the Django Admin. In extending User, I already had to add the following code:
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
However, I would like the information for the Business or Student aspects of the user to show up in the Django admin when that User is pulled up, but the ForeignKey part of the model is in the Student and Business model since every Student/Business has a User but every User has only one Student or one Business object connected with it. I'm not sure how to add a conditional Inline for the Admin.
Question: Given this structure and these concerns, what is the best way to set up this site, particularly the data model?
This is not a complete solution, but it will give you an idea of where to start.
Create a UserProfile model in mainsite. This will hold any common attributes for both types of users. Relate it to the User model with a OneToOne(...) field.
Create two more models in each app, (student/business), Business and Student, which have OneToOne relationships each with UserProfile (or inherit from UserProfile). This will hold attributes specific to that type of users. Docs: Multitable inheritance / OneToOne Relationships
You may add a field in UserProfile to distinguish whether it is a business or student's profile.
Then, for content management:
Define the save() functions to automatically check for conflicts (e.g. There is an entry for both Business and Student associated with a UserProfile, or no entries).
Define the __unicode__() representations where necessary.
I hope I understood your problem... maybe this can work? You create a abstract CommonInfo class that is inherited in into the different Sub-classes (student and businesses)
class CommonUser(models.Model):
user = models.OneToOne(User)
<any other common fields>
class Meta:
abstract = True
class Student(CommonUser):
<whatever>
class Business(CommonUser):
<whatever>
In this case the models will be created in the DB with the base class fields in each table. Thus when you are working with Students you run a
students = Students.objects.get.all()
to get all your students including the common information.
Then for each student you do:
for student in students:
print student.user.username
The same goes for Business objects.
To get the student using a user:
student = Student.objects.get(user=id)
The username will be unique thus when creating a new Student or Business it will raise an exception if an existing username is being saved.
Forgot to add the link