Using django, say I have model classes A and B, representing different types of Companies. Each Company may have multiple Users associated with it. Obviously I'd like to use django's User model, to get the login, etc. goodness. How would I go about doing that? Would I add a UserProfile that has two foreign keys, one to A and one to B (and the one that isn't null points to the company that the User works for)? Or is there another way?
thanks!
Use inheritance: define a superclass for Company, with the common fields, and then inherit that class and add the stuff ClassACompany and ClassBCompany need.
This way the UserProfile can have a foreign key to Company. If you need to get from the company to the specific type of company, you can do that as described in the docs.
why dont you just have one class for Company? that'll make your system much, much simpler.
you can then have specific fields inside Company that will let you determine whether it's of type A or B (what's the difference anyway?)
If you really must have different fields inside CompanyA and CompanyB then you can have them both derive from a common Company class which your ForeignKey will point to.
You would need to reference the Company model, and if need be, subclass Company with CompanyA and CompanyB. For simplicity, your Company class could have a type attribute with possible A and B values, then you could avoid subclassing.
Related
I'm wondering what is the best way to represent the models, because there are some fields in common and others that change according to the category.
Example: Common fields: (title, author, content, photo, references)
Category and its specific fields:
Biography (birth data, death data, occupation)
Commemorative date (data, description)
Music (artist, album, year, musical style)
The best would be to create a generic model with common fields and others inherit from it (abstract models)?
Create a model for each category, ie repeating the common fields?
Create a single model with the common fields and have a category field that when selected would display the category-specific fields in django-admin? In that case, I suppose it would be done with jquery? Any references? There is nothing the material has on this on the internet.
Note: All user interaction to register is in django-admin.
From the docs:
Often, you will just want to use the parent class to hold information that you don’t want to have to type out for each child
model. This class isn’t going to ever be used in isolation, so
Abstract base classes are what you’re after.
If you’re subclassing an existing model (perhaps something from another application entirely) and want each model to have its own
database table, Multi-table inheritance is the way to go.
So if you don't want the parent class to have it's own table, abstract model is the way to go.
I have a User model with some fields. Some of them will require feedback, are they correctly filled (if not, specific message will be displayed on user profile).
The problem is, how to represent 'invalid' fields in database. My idea is to create another model (call it ExtUser) with OneToOneField to User. And ExtUser should have same fields' names as User, but their types will be all boolean, determining whether field is filled in correctly. For example, if User has a field called email:
email = models.CharField(max_length=100)
ExtUser would have following field:
email = models.BooleanField(default=False)
Here's a problem with this approach. How am I supposed to create fields in ExtUser? Of course I can create them manually, but that would be breaking of DRY principle, and I'm not going to do that. The question is, can I add fields to model dynamically, and have them in database (so I assume it would require to be called before migrate)?
I have django 1.8 and I don't want to use any external modules/libraries.
If someone has an another idea of how to represent that data in database, please add comment, not a reply - as this question is about creating fields dynamically.
You will need to do this manually.
Python does not disallow this behavior; you can take a look at this SO response on dynamically created classes, but Django will not be able to interpret the output. In particular, Django relies on the models to create the SQL tables for the application, and there is essentially no way for this to occur if you model is not statically defined.
In this case, I don't think you have to worry much about DRY; if you need a separate model with fields which happen to be related to, but different from, another model, I think it's probably ok.
Finally, I'm unsure what your goal is, but you could probably define some functions which can determine how "correct" the fields of the user are. This is how I would recommend solving this problem (if it applies).
I'm pretty new to Django and Python. I'm trying to create some "category-dependent" models.
I have a Product model and i want to have category-dependent atributes. Example:
If i select "Permanent Dyes" in the category of my product i want to have specific atributes for my user to fill.
I don't want to create different models for every type of product i'm going to manage.
Is there any workaround to do this and keep using the django-admin?
Thanks in advance!
Model inheritance seems like it would help in this situation. Using it, you can have an abstract Product base class and then use Meta to add different product-dependent characteristics you need. It may require different models, but you would only need to add the attributes you needed, like below
class Product(models.Model):
....
class ProductA(Product):
class Meta:
....
This will allow you to have general properties in the Product class, such as price, etc., but use the subclass as a way to distinguish between different products.
Hope that helped in some way!
I see another question on stackoverflow.com whose title seems similar but that doesnot fulfil my requirements and my users are very different so only different roles will may be not work well. I have scenario of job portal where one type of user is a company which have different attributes different functionality while other is candidate who can show his profile and resume e.t.c., they will have different URLs. So they are totally different but common thing is that they are both Registered users. They will use login forms, they will have change password and I intend to use User class for that purpose.
Actual problem I am facing is about UserProfile class usage. UserProfile is use for profiles but in my case these two users are totally different and need many different things in profile. Also I will may be add more user types in system in future. While in django, we tell about profile is by adding this single model in settings.py
AUTH_PROFILE_MODULE = ‘accounts.userprofile’
So is there a way to do this by using some sort of inheritance or abstract class in django or some other way so that I can get intended functionality and can use django Profiles?
EDIT: Ok, upon further inspection, my previous answer clearly will not work.
I had advocated abstracting the UserProfile class. However, if you do that, you cannot instantiate it, so you're back to square one.
However, you can use Multi-table inheritance to achieve what you want. See this in the docs and this Quora thread that provided the inspiration.
The code I posted before remains largely unchanged, save for the exclusion of the Meta sub-class and the abstract variable.
class UserProfile(models.Model):
# Some Stuff
class CompanyProfile(UserProfile):
# Some more stuff
class CandidateProfile(UserProfile):
# Even more stuff
Here's the deal:
I got two db models, let's say ShoppingCart and Order. Following the DRY principle I'd like to extract some common props/methods into a shared interface ItemContainer.
Everything went fine till I came across the _flush() method which mainly performs a delete on a related object set.
class Order(models.Model, interface.ItemContainer):
# ...
def _flush(self):
# ...
self.orderitem_set.all().delete()
So the question is: how do I dynamically know wheter it is orderitem_set or shoppingcartitem_set?
First, here are two Django snippets that should be exactly what you're looking for:
Model inheritance with content type and inheritance-aware manager
ParentModel and ChildManager for Model Inheritance
Second, you might want to re-think your design and switch to the django.contrib content types framework which has a simple .model_class() method. (The first snippet posted above also uses the content type framework).
Third, you probably don't want to use multiple inheritance in your model class. It shouldn't be needed and I wouldn't be surprised if there were some obscure side affects. Just have interface.ItemContainer inherit from models.Model and then Order inherit from only interface.ItemContainer.
You can set the related_name argument of a ForeignKey, so if you want to make minimal changes to your design, you could just have ShoppingCartItem and OrderItem set the same related_name on their ForeignKeys to ShoppingCart and Order, respectively (something like "item_set"):
order = models.ForeignKey(Order, related_name='item_set')
and
cart = models.ForeignKey(ShoppingCart, related_name='item_set')