Is there a way to build dynamic models in Django? - python

I am currently building a project in Django, and I was wondering if is there a way to build a dynamic model. I want to create a model with a group of user, and the table structure is the following:
Group Name
User 1
User 2
User 3
User ...
But I want to make users dynamic, I mean, if the group has only 2 users the model will only put 2 users fields in the model, and if the group has 10 user the model put 10 users fields in the model.
Does someone know a way to do this? Is it even possible?
I hope I made it clear enough for you guys!
If you have any questions please post in the comments and I will answer as fast as I can.
Sorry for the english tho! Not my main language.

Think this way.
One group may have many users and one user can be in may groups you can use ManyToManyField.
So you need something like:
# default user model or custom user model
class User():
...
def __str__(self):
return self.username
class Group(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
users = models.ManyToManyField(User)
class Meta:
ordering = ['-id']
def __str__(self):
return self.title

this is not possible in django. because the models should be clear to make tables in database. but you can handle this with many-to-many relationship. as the django documents say link

Related

How Do I Represent Student-Lecturer Relationship in Django?

So I'm trying to make a web app that is meant to aid interaction between students and teachers.
However, I need to know how to structure the model of relationships in Django. Here are 2 things you should know:
A teacher can have many students (users) under him or her.
A student can only have one user as his teacher.
In other words, teachers are meant to have as many students as possible, while each student can only have one teacher.
How should I represent this in Django? And what's the best way to manage this relationship? For the latter question, I'm thinking about creating a class that looks like this:
class Relationship(models.Model):
##student and lecturer models shall inherit the User class; hence, the
student = models.ForeignKey(User, related_name = 'lecturer_set')
lecturer = models.ForeignKey(User, related_name = 'student_set')
class Meta:
unique_together = ('student', 'lecturer')
PS: I know the above class might be wrong. Just trying to explain what I need to implement in the Relationship class.
This is a standard one-to-many relationship, which is represented in Django by a simple ForeignKey.
class Student(models.Model):
teacher = models.ForeignKey(Teacher)
You don't need the Relationship model at all.

Foreign key model in Django Admin

I have two user roles in Django:
Commercials
Sellers
I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using StackedInline, TabularInline etc.
The problem I have is I need to associate users to this models in order to authenticate, login, etc. In admin I need to create a user (in an inline way, not dropdown box)
This is my code:
In models.py:
class Commercial(models.Model):
name = models.CharField(max_length=255, null=True)
user = models.OneToOneField(User, null=True)
class Seller(models.Model):
name = models.CharField(max_length=255, null=True)
commercial = models.ForeignKey('Commercial')
user = models.OneToOneField(User, null=True)
In admin.py:
class SellerAdmin(admin.StackedInline):
model = Seller
extra = 1
class CommercialAdmin(admin.ModelAdmin):
inlines = [SellerAdmin]
admin.site.register(Commercial, CommercialAdmin)
I need to edit, create, users etc. related to this models inline not in a modal window, Is there any way?
There is no way to make a reverse relation (so to say) in the form of Inlines. The Django admin panel doesn't have that ability by default.
What you could do is unregister the default UserAdmin, create a new Admin panel by inheriting the original one, and add this Seller as an Inline. There is still the issue that Django doesn't support multiple inlines, hence, you will not be able to use the Commercial model in the same admin page.
To fix that, you could refer to this information from the doc which shows how to overwrite the automatically created ModelForm for a particular ModelAdmin.
This will however not be that helpful as they are a lot of work. I would rather suggest implementing a workaround in how your application is used, rather than complicating it this much. Depends on the needs of the project, whether you need to go through this much trouble
Django nested inlines library might help you.

Django custom user models in 1.8

I'd like to create a project for finding mentor.
In planning i thought, that it would be nice to separate two models on registration users: for students (those, who wants to find mentor) and mentors.
Built-in django user model isn't like that. I plan to add more fields, also several fields can be the same: in students and in mentors.
Can you give me live example of customing model? Would be nice, if you have smth in git or other code sharing.
Shoudl I inherit mentor model from students, because it can have same fields: email, name, surname, etc?
What additional code should i write for working custom model? I read docs and found unknown for me - managers. Should i also customize managers?
If i get success in custom model what problems can i meet in future for auth,registration, changing passwords for this custom model?
Creating 2 separate models is not recommended here. You will need to have separate login process and be careful to avoid problems with sharing pk between users in separate tables. Also I'm pretty sure that django won't allow that.
Better choice is to make 2 profile models, as described in Extending the existing User model. In one of profiles you will store specific data for student and in other specific data for mentors.
Your website has two intended users, so there is no problem with creating two user models. Just make sure to inherit them from user model
from django.contrib.auth.models import User
class Student(User):
...
class Mentor(User):
...
You shouldn't re-invent the wheel, except you really want to learn and practice core features of Django. Just add some add-on library like userena, which "supplies you with signup, signin, account editing, privacy settings and private messaging". In general userena gives an additional UserenaBaseProfile model which is connected to built-in User model. So you can just inherit this model for the Student and for the Mentor:
from django.contrib.auth.models import User
from userena.models import UserenaBaseProfile
class CustomProfile(UserenaBaseProfile):
user = models.OneToOneField(User, unique=True)
common_field_for_all_children = models.IntegerField()
class Meta:
abstract = True
class Student(CustomProfile):
something_student_related = models.IntegerField()
class Mentor(CustomProfile):
something_mentor_related = models.CharField(max_length=255)

Independent models relationship

Let's say i have several different models in django project. Now i need to implement reddit-like rating system, that can be easily added to any model in the project. Model look like this:
class Rating(models.Model):
vote = models.IntegerField(blank=False, null=False)
user = models.ForeignKey(User)
The question is - how to connect this 'abstract' model to any other model in project?
You need generic relations from built-in contenttypes framework.
First (and with the disclaimer that I don't know anything about Reddits rating system), unless you want users to put in ratings from negative millions to positive millions, why not use choices?
Now to the problem at hand: A model that is rate-able should have a relation that allows many ratings to one model. Unfortunately this means that none of the relationship fields in Django will work. The absolute simplest solution to this is to have the rating in the actual model.
If you don't want to copy-paste the rating fields you can use an abstract model and inherit from that:
class RateableModel(models.Model):
rating = models.Integerfield(...)
rating_user = models.ForeignKey(User)
class Meta:
abstract = True
class SomeModelThatCanBeRated(RateableModel):
# Fields for this model

Creating Schema for Users with Friends without many to many relationship?

I'm working on my first Django app and trying to create the models for it but am stuck on how to create what I think should be a simple model relationship. I want to create a model for a user, with typical attributes like username, password(hash of course), date joined, etc. Then would like to be able to link this user to all of their friends/followers on the site. But where i'm stuck is how i setup that relationship since one user can have many friends, I can key off that primary key for the User table, but how do i create a model for the friends table that has the primary key for the user table serve two functions, one as the mapping to the user, and the mapping to the primary key for all of their friends?
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=200)
dateJoined = models.DateField('date joined')
class Friends(models.Model):
user = models.ForeignKey(User)
First, I would recommend you not create your own User model, instead use the one that comes built in Django. It takes care of all the fields that you're looking for.
Second, I would also create a "profile" model and store my friends in that. Have a look here on what profiles are: http://docs.djangoproject.com/en/1.2/topics/auth/#storing-additional-information-about-users
Third, in your profile model, I would add a field for friends exactly as it's shown here: http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
You can then access friends for a user like user.get_profile().friends.all(). A bit verbose, but keeps things clean.
CREATE TABLE friends (user_id int, friend_id int)
Both columns reference the user ID. I don't know Django models, but guessing from your code, it'd look like:
class Friends(models.Model):
user = models.ForeignKey(User)
friend = models.ForeignKey(User)

Categories

Resources