I have a normal Django model. I want to give a certain user the ability to add custom fields. I want the model to update during runtime and the database migrations to apply and then the user can do regular CRUD operations.
Example of a simple Model is
class location(models.Model):
AuotLocationID = models.CharField(max_length=200)
LocationID = models.CharField(max_length=200)
Name = models.CharField(max_length=200)
The user should be able to add other model fields such as Postal Code, Population, etc. Also each instance of the model should be linked to each user. For example Bob may want to track certain fields for his location and John may want some other fields.
Thank you for your help
Related
class Building(models.Model):
address = models.CharField(max_length=20, primary_key=True)
employers = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="employers",
blank=True)
Suppose n users of model type User and m buildings of model type Building (m << n). I would like in the Admin page to be able to put users into building in the unique way:
a user can be in maximum one building.
a building can have many employers. It can be empty too.
in the Admin page, in the Employers selection widget, in the UPDATE
mode, exclude users that belong to another building. In the CREATE
mode, show only users without a building.
Stack: Django, MySQL.
So, basically you need inside User model one field with Foreign key relationship with Building and you can query it with related name.
example:
class User(AbstractUser):
"""
Your user model
"""
building = models.ForeignKey(Building, related_name='building_employers', on_delete...)
...
Later you can query employers with building_object.building_employers.all()
For question number 3, please check:
https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.TabularInline
I am new to Django and relational databases coming from the Firebase world. I am having trouble figuring out the best modeling for a Doctor-Patient booking app and generally how relational DBS works best; I would like to minimize future problems by doing a great job now. I am going to use Django and Django Rest Framework at the backend to feed a React frontend.
So far, I've created these models in a clinic app. Patients and Secretaries are going to be part of the users, and so are Doctors. I then create the Serializers and Viewsets for the API.
class Clinic(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
accepted = models.BooleanField(default=False)
class Doctor(models.Model):
clinic = models.ManyToManyField(
Clinic, related_name="doctor")
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.EmailField(max_length=240, default="email")
appointment_duration = models.IntegerField(default=20)
class Secretary(models.Model):
clinic = models.ForeignKey(
Clinic, on_delete=models.CASCADE, related_name="secretary")
name = models.CharField(max_length=200)
email = models.EmailField(max_length=240, default="email")
doctors_responsible_for = models.ManyToManyField(Doctor)
class Patient(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.EmailField(max_length=240, default="email")
date_of_birth = models.DateField()
age = models.PositiveIntegerField(default=0)
Should I create a User model to be able to differentiate users (Doctors, Secretaries and Patients)? They are all going to be able to register and log in and each will see different things on the page. Should I just return 'is_doctor' or 'is_secretary' from the serializer API and show different content from there?
I'm confused as to how I would connect a User model with a Doctor or Secretary model, for example, or if I even need to since they're all users...
How would I differentiate users (Doctor, Secretary, Patient) at the registration moment? E.g., for each of them to have a different registration form with a boolean for is_doctor, is_secretary?
I can't to come up with a solution for storing booked appointments. I'm wondering if I should create a new model, Bookings, for saving bookings but I'm not sure if this booking model should hold every single booking (from any patient to any doctor), considering this app will be used by a lot of people. Or should bookings be under each patient and each doctor?
In this case, secretaries will also be able to manually add bookings to a Doctor calendar and add the patient as well.
I am building all of this in a single app, clinic, perhaps it is recommended to create different apps for this?
Each doctor will need to have its own calendar for this app to work, with say, 'day 12, blocks of 20mins from 09:00 to 11:30'. Should I create a Calendar model? Or how is it best to achieve this? How to best come up with this model? This calendar will be populated with blocks of time from whatever each doctor chooses as their availability.
First of all, I'm a django noob, so please read the following with that it mind.
Looks pretty good - the only thing I see missing is how you link patients to clinics and or doctors.
The other thing I notice is how doctors can have multiple clinics. I assume each clinic has its own calender, rather the doctor itself? Or maybe both? i.e. Even if a doctor was available on his calendar, he might not have a room at the clinic for the patient as other doctors' calenders would clash with it.
Personally, I wouldn't create a new app for clinic unless you want to model it in far more detail. Keep it simple initially.
Also, if you're allowing doctors, secretaries, and patients to login to your site, it might be better to have consumer/provider class model descending from custom user. ideas...
I would start thinking about the problem in more abstract terms. Service/provider/consumer.
But, I think you're on the right track.
I can throw in some ideas.
Models
I think you are on the right track. You just need to associate models Doctor, Secretary and Patient to the User model. I would recommend you to create a custom user model inherited from AbstractUser.
In this model, you can either add a choice field with choices for each type of user. link to docs
Also, you need to link the user model with the correct model.
One way to do is to have a OneToOneField for the user model in all your user type models: Doctor, Secretary, Patient
Or you can explore generic relations. It will further streamline things for you. link to docs.
Signup
You can provide a field for users to select at the time of signup, or provide separate links to signup and handle things at the backend. Something like If you are a doctor, click here to signup. In both cases, you'll need to override the signup process.
So a signup link can look like: /signup/doctor/ or /signup/patient/. All signup will be using the same view, just different url kwargs. link to docs
You can just create rows on the relevant model for user type on form success.
Booking
Yes, you need to create a separate model, and you can store all your bookings in this model. Doesn't matter how many users use your app. Just use a good database solution, like Postgres. There are ways to optimize your queries, like indexing, don't worry about it for now. Just make sure to save all references like, patient, doctor, created, last modified, created by which user, from_datetime, to_datetime, etc.
It would be better to handle the 20 min appointment blocks in forms.py.
You can create a list of acceptable time blocks, so that if in future you want to change this time to say 30 min, its easily doable. Just handle all validations at the form level and it should do the trick.
Hello Awesome People!
Such a question that I have made a lot of searches for it. I am done building a website two(2) months ago, but today The team decides to track every time an instance has been added to a Model in ManyToManyField() fields.
I was thinking using the through argument to point to the model that will act as an intermediary may work but not at all in my case (70%). Just Because I want to have a unique intermediary model that will record for all ManyToManyField()
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateTimeField(auto_now_add=True)
Ah! Something is required. I need to explicitly specify foreign keys to the models that are involved in the many-to-many relationship.
Django ContentType may anticipate for all my models, but it's not working, I wonder why? it also contains ForeignKey (the one required by an intermediary model).
Do I really need to edit all my ManyToManyField fields and create Model as much as ManytoManyField? is there a way to record date_joined without creating an intermediary model for each?
Are you perhaps looking for something like django admin's LogEntry model?
LogEntry contains the ContentType of the model instance that has changed, the id of the instance, the type of change and an abstract change message. With all of that you can retrace changes made to instances.
In django admin, the views take care of adding records to LogEntry via three methods log_change/addition/deletion: click.
I have an account model in django which has a foreignkey to Payment and a onetoone to Address.
In the Account section in the admin, I can edit a specific model and edit the fields payment and address via a select widget. However how can I filter the options so that it only shows related models. (ie not every address or payment from every user, only the ones from that user).
The RelatedOnlyFieldListFilter seems to only apply to the model list view. Is there a way to use this in the model edit view?
What you are probably looking for is call inlines. It allows you to edit related object directly in the parent model form which in this case would be the Account model. Here is an example of implementation:
class Account(models.Model):
name = models.CharField(max_length=100)
class Payment(models.Model):
account= models.ForeignKey(Account, on_delete=models.CASCADE)
amount= models.CharField(max_length=100)
class Adress(models.Model):
account= models.OneToOneField(Account, on_delete=models.CASCADE)
adress= models.CharField(max_length=100):
class AccountAdmin(admin.ModelAdmin):
inlines = [
Paymentinline,
Adressinline,
]
Note that this is not a complete implementation (you will need to construct both inlines), follow the documentation on inlines for further information but above are the basics to it.
I have a model similar to the following (simplified):
models.py
class Sample(models.Model):
name=models.CharField(max_length=200)
class Action(models.Model):
samples=models.ManyToManyField(Sample)
title=models.CharField(max_length=200)
description=models.TextField()
Now, if Action.samples would have been a ForeignKey instead of a ManyToManyField, when I display Action as a TabularInline in Sample in the Django Admin, I would get a number of rows, each containing a nice form to edit or add another Action. However; when I display the above as an inline using the following:
class ActionInline(admin.TabularInline):
model=Action.samples.through
I get a select box listing all available actions, and not a nifty form to create a new Action.
My question is really: How do I display the ManyToMany relation as an inline with a form to input information as described?
In principle it should be possible since, from the Sample's point of view, the situation is identical in both cases; Each Sample has a list of Actions regardless if the relation is a ForeignKey or a ManyToManyRelation. Also; Through the Sample admin page, I never want to choose from existing Actions, only create new or edit old ones.
I see your point but think of a case where you might need to use custom through model (table). In that case the admin inline form would include the fields for that intermediate model since thats the model you asked the admin to create the form for.
e.g.
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
The admin should display the form for the Memebership model cause thats the model the editable instance is related to.
In your case the through model contains only the 2 foreign keys (1 for the Action model and 1 for the Sample) ands thats why only the list of actions appear.
You could do what you are asking for if django admin supported nested inlines (there is an open ticket about that).