Now I had a problem
RuntimeError: Can't resolve dependencies while running tests and after long debugging We found that a forigen key relationship is the problem
Yet we need this relation in our app
I have to get an owner relation to Django Groups
The models like that:
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
parent = models.ForigenKey('self', null=True)
django.contrib.auth.models import Group
Group.add_to_class('owner', models.ForeignKey('users.UserAccount',
blank=True,
null=True,
related_name='groups_created'
))
As I need to define an owner to the groups as I have my specific hierarchy system for users so no one can see others groups
So what Can I do?
Update - Solution
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
hierarchy_id = models.PositiveIntegerField()
django.contrib.auth.models import Group
Group.add_to_class('hierarchy_id', models.PositiveIntegerField(null=True))
#script populate hierarchy
h_id=0
for user in users:
if user.is_parent:
then user.hierar...... = h_id
and so on.. I populated hierarchy ID instead of relation
Thanks
Actually I found you can do a circular dependency without your knowledge, in case you do a relation and migrate it then do the reverse relation after a while then migrate it , it will not clash but when both migrated instantly in tests for example it will clash. so I tried this solution and tested, after a year from asking the question, it is working well.
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
hierarchy_id = models.PositiveIntegerField()
django.contrib.auth.models import Group
Group.add_to_class('hierarchy_id', models.PositiveIntegerField(null=True))
#script populate hierarchy
h_id=0
for user in users:
if user.is_parent:
then user.hierar...... = h_id
Related
I have a simple view on the DB which selects from other DB's tables located on the same MSSQL Server to ultimately serve the collected info as a dropdown to the user.
So far I've added the Model with inspectdb:
class AutPricePlanView(models.Model):
priceplan_name = models.CharField(db_column='PricePlan', max_length=50, blank=True, unique=True)
class Meta:
managed = False # Created from a view. Don't remove.
db_table = 'AUT_PricePlanView'
Also I have a second existing (Django Native) Model where I want to use the values from the view for a Dropdown Field (to keep everything in sync):
class PricePlanDownload(models.Model):
requesting_user = models.CharField(blank=True, default=None, max_length=50, null=True)
requested_at = models.DateTimeField(auto_now_add=True)
document = models.FileField(upload_to='documents/price_plan_uploads/%Y/%m/%d', blank=True)
priceplan = models.ForeignKey(AutPricePlanView, null=True, on_delete=models.DO_NOTHING)
Makemigrations works fine but when I try to actually migrate I get the following issue: (shortened it a little bit)
django.db.utils.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Foreign key references object 'AUT_PricePlanView' which is not a user table. (1768) (SQLExecDirectW)")
I would be really grateful if someone had an idea or a workaround since I can't figure out what the heck this has to do with a "user" table...
Since the view is not actually a table, you cannot set Foreign Key constraints. Since ForeignKey's default db_constraint value is True, Django tries to set Foreign Key constraints when performing migrations. This is the reason the migration fails.
So, you can turn off the db_constraint option. And you can remove the existing migration file, and re-create the migration file. Then, the migration will success and you can keep everything in sync.
class PricePlanDownload(models.Model):
... other fields ...
priceplan = models.ForeignKey(AutPricePlanView, null=True, on_delete=models.DO_NOTHING, db_constraint=False)
Pro Tip: You can review migration's SQL using python manage.py sqlmigrate <appname> <migration number>, like python manage.py sqlmigrate yourapp 0002.
Update: You can define __str__ to display the correct value at the dropdown menu.
class AutPricePlanView(models.Model):
priceplan_name = models.CharField(db_column='PricePlan', max_length=50, blank=True, unique=True, primary_key=True)
# null=False by default. See https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L132
def __str__(self):
return self.priceplan_name
class Meta:
managed = False # Created from a view. Don't remove.
db_table = 'AUT_PricePlanView'
I would like to create a view with a table that lists all changes (created/modified) that a user has made on/for any object.
The Django Admin site has similar functionality but this only works for objects created/altered in the admin.
All my models have, in addition to their specific fields, following general fields, that should be used for this purpose:
created_by = models.ForeignKey(User, verbose_name='Created by', related_name='%(class)s_created_items',)
modified_by = models.ForeignKey(User, verbose_name='Updated by', related_name='%(class)s_modified_items', null=True)
created = CreationDateTimeField(_('created'))
modified = ModificationDateTimeField(_('modified'))
I tried playing around with:
u = User.objects.get(pk=1)
u.myobject1_created_items.all()
u.myobject1_modified_items.all()
u.myobject2_created_items.all()
u.myobject2_modified_items.all()
... # repeat for >20 models
...and then grouping them together with itertool's chain(). But the result is not a QuerySet which makes it kind of non-Django and more difficult to handle.
I realize there are packages available that will do this for me, but is it possible to achieve what I want using the above models, without using external packages? The required fields (created_by/modified_by and their timefields) are in my database already anyway.
Any idea on the best way to handle this?
Django admin uses generic foreign keys to handle your case so you should probably do something like that. Let's take a look at how django admn does it (https://github.com/django/django/blob/master/django/contrib/admin/models.py):
class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)
So, you can add an additional model (LogEntry) that will hold a ForeignKey to the user that changed (added / modified) the object and a GenericForeignKey (https://docs.djangoproject.com/en/1.7/ref/contrib/contenttypes/#generic-relations) to the object that was modified.
Then, you can modify your views to add LogEntry objects when objects are modified. When you want to display all changes by a User, just do something like:
user = User.objects.get(pk=1)
changes = LogEntry.objects.filter(user=user)
# Now you can use changes for your requirement!
I've written a nice blog post about that (auditing objects in django) which could be useful: http://spapas.github.io/2015/01/21/django-model-auditing/#adding-simple-auditing-functionality-ourselves
I filled datas into postgreSQL without type foreignkey at first.
here is my models.py
class BeverageMenu(models.Model):
brand = models.CharField(max_length=255, null=True)
area = models.CharField(max_length=50, blank=True, null=True)
class DMenu(models.Model):
dmenu = models.ForeignKey(BeverageMenu,null=True,blank=True)
category = models.CharField(max_length=255, null=True)
product = models.CharField(max_length=255, null=True)
and I use this way to update the foreignkey:
>>> from psql.models import BeverageMenu,DMenu
>>> menu1 = BeverageMenu.objects.get(id=1)
>>>product = DMenu.objects.filter(area='North')
>>>product.update(dmenu=menu1)
And I want to know could I use SQL directly to do this ?
I try this but fail
INSERT INTO psql_dmenu(category,product,dmenu) VALUES ('hot','soup',1),
ERROR: column "dmenu" of relation "psql_dmenu" does not exist
You could, but why would you want to? Django has a model layer for a reason, which is to make the database easier to deal with and less dependent on SQL.
However, for your problem, the issue is that the underlying database column for a ForeignKey includes the prefix _id: so your field is dmenu_id.
I have two models: Industry and Employer, as per below:
class Industry(models.Model):
name = models.CharField(max_length=255, unique=True)
class Employer(models.Model):
industry = models.ForeignKey(Industry)
name = models.CharField(max_length=255, unique=True)
The problem is that not all of the industries have employers yet... I want to get a list of all industries that have atleast one employer mapped to them, rather than getting them all. Is this possible with the ORM not with just regular SQL? I tried to find this in the django docs and coudlnt..
This is a classic problem for Django Annotations
Try:
from django.db.models import Count
Industry.objects.annotate(num_employers=Count('employer').filter(num_employers__gt=0)
I have a simple userprofile class in django such that
class Profile(models.Model):
user = models.OneToOneField(User,unique=True)
gender = models.IntegerField(blank=True, default=0, choices=UserGender.USER_GENDER,db_column='usr_gender')
education = models.IntegerField(blank=True, default=0, choices=UserEducation.USER_EDU,db_column='usr_education')
mail_preference = models.IntegerField(blank=True, default=1, choices=UserMailPreference.USER_MAIL_PREF,db_column='usr_mail_preference')
birthyear = models.IntegerField(blank=True, default=0,db_column='usr_birthyear')
createdate = models.DateTimeField(default=datetime.datetime.now)
updatedate = models.DateTimeField(default=datetime.datetime.now)
deletedate = models.DateTimeField(blank=True,null=True)
updatedBy = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_update')
deleteBy = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_delete')
activation_key = models.CharField(max_length=40)
key_expires = models.DateTimeField()
You can see that deletedBy and updatedBy are foreign key fields to user class. If I don't write related_name='%(class)s_user_update' it gives me error (I don't know why).
Although this works without any error, it doesn't push the user id's of deletedBy and updatedBy fields although I assign proper user to them.
Could give me any idea and explain the related_name='%(class)s_user_update' part ?
Thanks
'%(class)s_user_update' implies that it is a string awaiting formatting. You would normally see it in the context:
'%(foo)s other' % {'foo': 'BARGH'}
Which would become:
'BARGH other'
You can read more about python string formatting in the python docs. String Formatting Operations
I can't see how the code you have would ever work: perhaps you want:
class Profile(models.Model):
# other attributes here
updated_by = models.ForeignKey('auth.User', null=True, related_name='profile_user_update')
deleted_by = models.ForeignKey('auth.User', null=True, related_name='profile_user_deleted')
# other attributes here
If it does work, it is because django is doing some fancy magic behind the scenes, and replacing '%(class)s' by the class name of the current class.
Notes on the above:
The consistent use of *snake_case* for attributes. If you must use camelCase, then be consistent for all variables. Especially don't mix *snake_case*, camelCase and runwordstogethersoyoucanttellwhereonestartsandtheotherends.
Where you have two attributes that reference the same Foreign Key, you must tell the ORM which one is which for the reverse relation. It will default to 'profile_set' in this case for both, which will give you the validation error.
Use 'auth.User' instead of importing User into the models.py file. It is one less import you'll need to worry about, especially if you don't use the User class anywhere in your models.py file.
You can read more about the related_name stuff here:
https://docs.djangoproject.com/en/1.3/topics/db/queries/#following-relationships-backward