I am working on one python(django framework) project in which i have one user model which has 1000 users. I want to make one another column named priority id and need to put default id values in that priority id column accordingly (you can see it below).
id
username
email
priority_id
1
abc
abc#gmail.com
1
2
xyz
xyz#gmail.com
2
ofcourse i can do it manually using admin panel but for 1000 users it is time consuming.
how do i change models.py or admin.py or something else to achieve this?
def save(self, *args, **kwargs):
self.priority_id = self.id
return super().save(*args, **kwargs)
I don't know why you would ever want to do this, but you can achieve it by adding adding a BigAutoField to your user model. The field will then auto-increment the values for new users according to available ids.
In your models where you define the user, add following field.
priority_id = models.BigAutoField(null=False, unique=True)
well, i tried it using shell and it worked:
p = Users.objects.all()
for x in p:
profile = Users.objects.get(pk=x.id)
profile.priority_id= x.id
profile.save()
you can use this for me its working fine first you have to create with a default value and then use this function in views and just call once it will update the value as in id.
def update_value(request):
totaldata = modelsName.objects.all()
for j in totaldata:
modelsName.objects.filter(id=j.id).update(myid=j.id)
return HttpResponse('Success')
Related
I am working with odoo 10 and have created a few fields, and have the following problem:
I created my own field (x_order_bestelldatum) in the module sale.order. When I confirm an offer, I enter the effective order date in this field.
Now, when I create an invoice, I want to read the x_order_bestelldatum field of the module sale.order in module account.invoice so that I can print the order date on the invoice.
How can I read out the field x_order_bestelldatum from model sale.order in model account.invoice?
Here is my code in file models.py, but it does not work:
from odoo import models, fields, api
class felder_saleorder(models.Model):
_inherit = 'sale.order'
x_order_bestelldatum = fields.Date(string="Bestelldatum")
class felder_invoice(models.Model):
_inherit = 'account.invoice'
sale_order = fields.Many2one('sale.order','sale_order')
x_bestelldatum = fields.Date(string="Bestelldatum",related='sale_order.x_order_bestelldatum')
x_lieferdatum = fields.Date(string="Lieferdatum")
That does not work (the field x_bestelldatum remains empty):
sale_order = fields.Many2one('sale.order','sale_order')
x_bestelldatum = fields.Date(string="Bestelldatum",related='sale_order.x_order_bestelldatum')
Well lets not do it your way plus I can't get it how you are doing it.
So, I am suggesting some other possibilities which might help you.
First lets talk about the sale order field whom you named as 'sale_order'.
There are two possible options with which you are entering data in the sale_order field.
1). Automatically through python
2). Manually by selecting from the list.
In case of entering data Manually you should use onchange function:
#api.onchange('sale_order')
def get_order_date(self):
if self.sale_order:
self.x_bestelldatum = self.sale_order.x_order_bestelldatum
In Case if you are automatically entering data through python then you can use monetary or create function to fill the field.
Create function:
#api.model
def create(self, vals):
new_record = super(felder_invoice, self).create(vals)
if new_record.sale_order:
new_record.x_bestelldatum = new_record.sale_order.x_order_bestelldatum
return new_record
Compute Funtion:
First you need to amend your field deceleration in py file like that
x_bestelldatum = fields.Date(string="Bestelldatum",compute="get_order_date")
Then you need to create a compute function for that:
#api.one
#api.depends('sale_order')
def get_order_date(self):
if self.sale_order:
self.x_bestelldatum = self.sale_order.x_order_bestelldatum
You can get the order date by using above mentioned functions and willbe able to get its value in reports/prints.
Hope it helps.
Cheers!
Thank you for your answer.
I have tried a few variants, but it still does not work. The field 'x_bestelldatum' in the module 'account.invoice' will always be empty.
This is what my code looks like:
class felder_invoice(models.Model):
_inherit = 'account.invoice'
x_lieferdatum = fields.Date(string="Lieferdatum")
sale_order = fields.Many2one('sale.order','sale_order')
x_bestelldatum = fields.Date(string="Bestelldatum",compute="get_order_date")
#api.one
#api.depends('sale_order')
def get_order_date(self):
if self.sale_order:
self.x_bestelldatum = self.sale_order.x_order_bestelldatum
Is that right? Are all fields from 'sale.order' transferred to the new locale field 'sale_order'?
sale_order = fields.Many2one('sale.order','sale_order')
I can't figure out how to populate choice form from db. I know about ModelChoiceForm but the problem seems to be slightly different.
I want user to choose which sector does he work in. For example: 'Finance','Electronics' etc. which I would do simple:
SECTOR_CHOICES = (('finance',_('Finance'),
'electronics',_('Electronics')...
))
But the problem is that I want admin of the web to be able to add new choices, remove choice etc.
What came to my mind is to create a simple Model called Sector:
class Sector(models.Model):
name = models.CharField(max_length=40)
and User would have new attribute sector = models.ModelChoice(Sector).
But I'm scared what would happend when admin changes or removes a sector which is already used, and more, what if he removes it and the sector attribute is required?
How to solve this problem?
I would just override the delete_model as custom action and there check if the selected sector object is in use.
def delete_model(modeladmin, request, queryset):
for obj in queryset:
if UserModel.objects.filter(sector=obj).exists():
# do not delete, just add some message warning the admin about it
else:
obj.delete()
class UserModelAdmin(admin.ModelAdmin):
actions = [delete_model]
# ...
I created a simple function which add users to a custom group. its working fine through button but the problem is i have to click the button every time the new user is create otherwise he will not be able to access the custom module so i want to overwrite create method of res.users and include add_to_group function. in result if someone signup through website they will be automatically added to the group.
here is my code
#api.multi
def add_to_group(self):
group = self.env['res.groups'].search([('name','=','Applicant)]) #search for my custom group
user_id = self.id #get the current user id
group.users = [user_id] #add the user to the group
Thanks in Advance
You should override create method in res.users model doing like:
#api.model
def create(self, vals):
res = super(ResUsers, self).create(vals)
res.add_to_group()
return res
Django 1.2.5
Python: 2.5.5
My admin list of a sports model has just gone really slow (5 minutes for 400 records). It was returning in a second or so until we got 400 games, 50 odd teams and 2 sports.
I have fixed it in an awful way so I'd like to see if anyone has seen this before. My app looks like this:
models:
Sport( models.Model )
name
Venue( models.Model )
name
Team( models.Model )
name
Fixture( models.Model )
date
sport = models.ForeignKey(Sport)
venue = models.ForeignKey(Venue)
TeamFixture( Fixture )
team1 = models.ForeignKey(Team, related_name="Team 1")
team2 = models.ForeignKey(Team, related_name="Team 2")
admin:
TeamFixture_ModelAdmin (ModelAdmin)
list_display = ('date','sport','venue','team1','team2',)
If I remove any foreign keys from list_display then it's quick. As soon as I add any foreign key then slow.
I fixed it by using non foreign keys but calculating them in the model init so this works:
models:
TeamFixture( Fixture )
team1 = models.ForeignKey(Team, related_name="Team 1")
team2 = models.ForeignKey(Team, related_name="Team 2")
sport_name = ""
venue_name = ""
team1_name = ""
team2_name = ""
def __init__(self, *args, **kwargs):
super(TeamFixture, self).__init__(*args, **kwargs)
self.sport_name = self.sport.name
self.venue_name = self.venue.name
self.team1_name = self.team1.name
self.team2_name = self.team2.name
admin:
TeamFixture_ModelAdmin (ModelAdmin)
list_display = ('date','sport_name','venue_name','team1_name','team2_name',)
Administration for all other models are fine with several thousand records at the moment and all views in the actual site is functioning fine.
It's driving me crazy. list_select_related is set to True, however adding a foreign key to User in the list_display generates one query per row in the admin, which makes the listing slow. Select_related is True, so the Django admin shouldn't call this query on each row.
What is going on ?
The first thing I would look for, are the database calls. If you shouldn't have done that already, install django-debug-toolbar. That awesome tool lets you inspect all sql queries done for the current request. I assume there are lots of them. If you look at them, you will know where to look for the problem.
One problem I myself have run into: When the __unicode__ method of a model uses a foreign key, that leads to one database hit per instance. I know of two ways to overcome this problem:
use select_related, which usually is your best bet.
make your __unicode__ return a static string and override the save method to update this string accordingly.
This is a very old problem with django admin and foreign keys. What happens here is that whenever you try to load an object it tries to get all the objects of that foreign key. So lets say you are trying to load a fixture with a some teams (say the number of teams is about 100), its going to keep on including all the 100 teams in one go. You can try to optimize them by using something called as raw_fields. What this would do is instead of having to calling everything at once, it will limit the number of calls and make sure that the call is only made when an event is triggered (i.e. when you are selecting a team).
If that seems a bit like a UI mess you can try using this class:
"""
For Raw_id_field to optimize django performance for many to many fields
"""
class RawIdWidget(ManyToManyRawIdWidget):
def label_for_value(self, value):
values = value.split(',')
str_values = []
key = self.rel.get_related_field().name
for v in values:
try:
obj = self.rel.to._default_manager.using(self.db).get(**{key: v})
x = smart_unicode(obj)
change_url = reverse(
"admin:%s_%s_change" % (obj._meta.app_label, obj._meta.object_name.lower()),
args=(obj.pk,)
)
str_values += ['<strong>%s</strong>' % (change_url, escape(x))]
except self.rel.to.DoesNotExist:
str_values += [u'No input or index in the db']
return u', '.join(str_values)
class ImproveRawId(admin.ModelAdmin):
raw_id_fields = ('created_by', 'updated_by')
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name in self.raw_id_fields:
kwargs.pop("request", None)
type = db_field.rel.__class__.__name__
kwargs['widget'] = RawIdWidget(db_field.rel, site)
return db_field.formfield(**kwargs)
return super(ImproveRawId, self).formfield_for_dbfield(db_field, **kwargs)
Just make sure that you inherit the class properly. I am guessing something like TeamFixture_ModelAdmin (ImproveRawIdFieldsForm). This will most likely give you a pretty cool performance boost in your django admin.
I fixed my problem by setting list_select_related to the list of related model fields instead of just True
I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!
Please show me an example of the code I need to write on my view.py and urls.py for perform this task.
Say you have a model Employee. To edit an entry with primary key emp_id you do:
emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()
to delete it just do:
emp.delete()
so a full view would be:
def update(request, id):
emp = Employee.objects.get(pk = id)
#you can do this for as many fields as you like
#here I asume you had a form with input like <input type="text" name="name"/>
#so it's basically like that for all form fields
emp.name = request.POST.get('name')
emp.save()
return HttpResponse('updated')
def delete(request, id):
emp = Employee.objects.get(pk = id)
emp.delete()
return HttpResponse('deleted')
In urls.py you'd need two entries like this:
(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),
I suggest you take a look at the docs
To do either of these you need to use something called queries.
check link below for really great documentation on that!
(https://docs.djangoproject.com/en/2.2/topics/db/queries/)
To Delete Data:
b = ModelName.objects.get(id = 1)
b.delete()
This will delete the Object of the model w/ an ID of 1
To edit Data:
b = ModelName.objects.get(id = 1)
b.name = 'Henry'
b.save()
This will change the name of the Object of the model w/ an ID of 1 to be Henry
Read the following: The Django admin site. Then revise your question with specific details.