Multiple references to the same model in another model in Django - django-models

Hi I have a lot of users in my system who are classified into different types. I want to store the address details of all those users. For instance the user could be a student, a school or a franchisee. All the users here could have an address information associated with them.
from django.db import models
from django.contrib.auth.Models import User
class Address(models.Model):
user = models.OneToOneField(User)
address = models.TextField()
class Student(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
class School(models.Model):
user_id = models.ForeignKey(User)
address = models.ForeignKey(Address)
contact_person_name = models.CharField(max_length=50)
In this scenario there are 2 references to the User model - one through user_id and another through address.user though they should be referring to the same instance. Is it a bad practice to have duplicate references?
I thought of leaving out the 'user' foreignkey in Address, but I think that the address can't exist without a user. How to better model this?

As you already mentioned in question duplication of same field in
a model is not a good Idea.
If these are your actual models, I would suggest you using abstract
models:
from django.db import models
from django.contrib.auth.Models import User
class Profile(models.Model):
user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related")
address = models.TextField()
class Meta:
abstract = True
class Student(Profile):
pass
class School(Profile):
contact_person_name = models.CharField(max_length=50)
This will generate two tables: students, schools with fields
user, address and user, address, contact_person_name
respectively.

Related

Managing a ForeignKey Relation in Django Admin

I am using django to create an inventory management system. There are two models store and retailer. Each retailer can only work in one store, but each store can have many retailer s.
Therefore, store is a ForeignKey in my retailer model. I have registered models in django admin. When I add a retailer I can choose a store.
When I add a store, I would like to be able to add a retailer to a store in the same page I add a store.
class Retailer(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
phone_number = models.IntegerField(default=00000000000)
store = models.ForeignKey(Store,null=True,on_delete=models.CASCADE)
class Store(models.Model):
name = models.CharField(max_length=200)
serial = models.CharField(max_length=200)
number_of_visitors = models.IntegerField(default=0)
it is called inline models:
https://books.agiliq.com/projects/django-admin-cookbook/en/latest/edit_multiple_models.html
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects
And you can find a lot of material about,
But you need something like this:
on your admin.py
#Create a class for inline display:
class RetailerINLINE(admin.TabularInline): #or stacked inline
model = Retailer
extra = 1
class StoreAdmin(admin.ModelAdmin):
.....
inlines = RetailerINLINE,

Multi user profile creation function

I'm django learner and I'm trying to design multiple userprofile system.
I recently saw the create_profile function for single userProfile. How can I redesign it to multi user profile creation function?
def create_profile(sender,**kwargs):
if kwargs["created"]:
user_profile=Student.objects.create(user=kwargs["instance"])
post_save.connect(create_profile,sender=User)
Have two models for each profile type. If you want, have them inherit from a base model but you don't need to.
class Student(models.Model):
user = models.ForeignKey(User)
# more fields
class Master(models.Model):
user = models.ForeignKey(User)
# more fields
myuser = User.objects.get(...)
student = Student.objects.create(user=myuser)
master = Master.objects.create(user=myuse

Place players only on one team with relational table

After going through several stackoverflows I still have yet to find something that solves this. I'm hoping it's just syntax as I'm a novice.
Admin:
from django.contrib import admin
from team_editor.models import Player, Team, TeamMembers
class PlayerInline(admin.StackedInline):
model = Player
class TMAdmin(admin.ModelAdmin):
inlines = (PlayerInline,)
# Register your models here.
admin.site.register(Team)
admin.site.register(Player)
admin.site.register(TeamMembers, TMAdmin)
Models:
class Player(models.Model):
firstName = models.CharField(max_length=30)
lastName = models.CharField(max_length=30)
class Team(models.Model):
teamName = models.CharField(max_length=30, unique=True)
class TeamMembers(models.Model):
team = models.ForeignKey(Team)
player = models.ForeignKey(Player, unique=True)
Error: class has no foreign key to class
I am using this setup since I want to view players on a team easily and change teams from one team to another (never on multiple)
Moved to many to many relation in team and dropped teammember table:
players = models.ManyToManyField(Player, blank=True, null=True)

django add boolean to many-to-many relationship

In my application I am adding a simple message service that allows a user to send out a message to a subset of other users on the system:
from django.db import models
from django.contrib.auth.models import User
class Message(models.Model):
timestamp = models.DateTimeField()
sender = models.ForeignKey(User)
recipients = models.ManyToManyField(User)
text = models.CharField(max_length=1000)
def __unicode__(self):
return '%s %s: %s' (self.sender.first_name,self.sender.last_name,self.timestamp)
class Meta:
ordering = ('timestamp')
However, I would like to record if each user has read the message, so would need to add a boolean field to the table holding the many-to-many relationship.
Should I do this by explicitly adding another model and using ForeignKey() only, or is there a more 'django' way of doing this?
Thanks
Never mind, my googling power were weak, just found the right place in the documentation:
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

Django querying an inherited model

I have something similar to the example below
from django.db import models
from django.contrib.auth.models import User
class a(models.Model):
user = models.ForeignKey(User)
class b(a):
value = models.IntegerField()
class c(a):
model_id = models.IntegerField()
I have a User instance assigned to variable current_user, is there any way I can make current_user.b_set work? Thank you for reading.
The FK is on a, not b, so there is no "b_set". You can query User for objects that have an a that have a b, but a_set is the only property you have.

Resources