I want to override Django Queryset Update method , to log the model changes in another table.I have override the method , but not able to find the id's of the rows which are going to get update.I am getting the fields which are getting changed from kwargs
I'm using Django v1.9.5.
I went through the docs of django-simple-history and django-reversion , but they don't log changes on update method.
class PollQuerySet(QuerySet):
def update(self, *args, **kwargs):
# save data into other table whose schema is
#(model_name,field_name,model_pk_id,old_value,new_value)
super().update(*args, **kwargs)
class ModelWithCustomManager(models.Model):
objects = PollQuerySet.as_manager()
class Meta:
abstract = True
Instead of overriding the update method, your may want to look in to signals. On pre-save and post-save you can grab data from the model and save it into a log table.
Related
I want to update fields in django admin site following the modification by the user of a given foreignkey field. I seek a way to trigger the event straight after foreignkey modification; not before/after save.
I looked for the creation of a custom signal through sender/receiver. Also I tried to find a similar signal as the m2m_changed. Perhaps one of these path could be the solution.
class Variety(models.Model):
specific_name = models.ForeignKey(CatalogList, on_delete=models.CASCADE)
def update_other_field(self):
#DO SOMETHING EACH TIME specific_name IS MODIFIED
Is there a way to trigger an event directly after a foreignkey is modified?
You can override save method of "parent" model :
class CatalogList(models.Model):
def save(self, *args, **kwargs):
super().save(*args, **kwargs) # Call normal save method
# Then do what you want with variety_set reverse relation
Using latest version of Django and DRF.
I have a rather complex requirement I can't find a solution for. I'll try to simplify it.
Let's say I have a model that has two fields. field_a and field_b
I have a ModelSerializer for it. I POST a request with its fields. The fields get validated with the model and then against my two serializer functions validate_field_a and validate_field_b. All is well.
Now I'd like my POST request to include a third field that is not a member of that model. let's call it field_c. I have a custom def create(self, validated_data): in my serializer which saves everything to the database.
with regards to field_c I would like to:
Custom Validate it. just like I do with the other two fields.
Require that it is mandatory for the whole request to succeed and if it's not, issue a "Field is required" error just like if I forgot to POST one of my required model fields.
Have the chance to take field_c and save it onto a totally different unrelated Model's row in the db.
I can't seem to get around that. If I add field_c to the fields meta - it throws an exception saying justifiably that field_c is not in my model. If I don't include it in fields, the validate_field_c which I really want to put there doesn't even get called.
What can I do?
You can add the custom field in your serializer as a write_only field and override the create method so that you can handle the custom field's value.
Something like this:
class MySerializer(serializers.ModelSerializer):
field_c = serializers.CharField(write_only=True)
class Meta:
model = MyModel
fields = ('field_a', 'field_b', 'field_c')
def validate_field_c(self, value):
if value is 'test':
raise ValidationError('Invalid')
return value
def create(self, validated_data, **kwargs):
field_c = validated_data.pop('field_c')
return MyModel.objects.create(**validated_data)
Don't use ModelSerializer for this - use a serializer that recreates the same fields as your model & include field_c as you would.
I understand that you want your model to do some of the work in the validation process but the design of DRF is such that it isolates these responsibilities. You can read more about it here. Basically, the serializer should be the one doing all the validation heavy-lifting.
Of course, this means that you'll have to explicitly define the validation methods in the serializer.
In your custom create() method you can create the model instance or do whatever you want in it as required.
I have a Django model with a Foreign key to a table that contains about 50,000 records. I am using the Django forms.ModelForm to create a form. The problem is I only need a small subset of the records from the table the Foreign key points to.
I am able to create that subset of choices in the init method. How can I prevent ModelForm from creating that initial set of choices?
I tried using the widgets parameter in the Meta method. But Django debug toolbar indicates the database is still being hit.
Thanks
The autogenerated ModelChoiceField will have its queryset initialized to the default. The widget is not where you are supposed to customize the queryset property.
Define the ModelChoiceField manually, initialize its queryset to be empty. Remember to name the ModelChoiceField the same as the one that would have been automatically generated, and remember to mention that field in the fields tuple. Now you can set the queryset from the constructor and avoid the database being hit twice.
If you are lucky (and you probably are, please test though), the queryset has not been evaluated during construction, and in that case, defining the ModelChoiceField manually is not required.
class YourModelForm(ModelForm):
your_fk_field_name = forms.ModelChoiceField(queryset=YourModel.objects.none())
class Meta:
model = YourModel
fields = ('your_fk_field_name', .......)
def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['your_fk_field_name'].queryset = ....
I have a deal model that contains two date field. First one is start_date and the other one is end_date. My aim is when I save a deal I want to update a readonly field which shows the substraction of these two date_field.
I try to write a widget however I can only get one of the fields. Here is my widget:
class DueToWidget(AdminDateWidget):
def render(self,name,value,attrs=None):
from datetime import timedelta
output = []
output.append(super(AdminDateWidget, self).render(name,value,attrs))
if value:
due_to = value + timedelta(days=1)
output.append(u'<p>Diff : %s</p>' % due_to)
return mark_safe(u''.join(output))
I'm adding one day to the selected date, how can I get the other field's value ? Or is there any other way to do this ?
If you don't mind having to refresh to see the diff (that is, you only see it after you save the model), then an easier approach is to add a readonly field in the admin, that points to a function, like this:
class MyModelAdmin(ModelAdmin):
readonly_fields = ('dates_difference',)
#add your other fields, or put it in a fieldset
fields = ('dates_difference',)
def dates_difference(self, model_instance):
return model_instance.end_date - model_instance.start_date
Since your goal is just to display extra information in the model's admin this is the place to put the code, not in a field's widget or the model's class.
As the readonly_fields documentation specifies, its behavior is nearly identical as the list_display, that is you can point it to attributes on both the model and the model's admin, and also to callables and methods.
Override save() in the model to save computed data.
def save( self, *args, **kw ):
self.diff = self.end_date - self.start_date
return super( YourModelClass, self ).save( *args, **kw )
Learn more by reading the Django documentation on the subject.
Given a model with ForeignKeyField (FKF) or ManyToManyField (MTMF) fields with a foreignkey to 'self' how can I prevent self (recursive) selection within the Django Admin (admin).
In short, it should be possible to prevent self (recursive) selection of a model instance in the admin. This applies when editing existing instances of a model, not creating new instances.
For example, take the following model for an article in a news app;
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
related_articles = models.ManyToManyField('self')
If there are 3 Article instances (title: a1-3), when editing an existing Article instance via the admin the related_articles field is represented by default by a html (multiple)select box which provides a list of ALL articles (Article.objects.all()). The user should only see and be able to select Article instances other than itself, e.g. When editing Article a1, related_articles available to select = a2, a3.
I can currently see 3 potential to ways to do this, in order of decreasing preference;
Provide a way to set the queryset providing available choices in the admin form field for the related_articles (via an exclude query filter, e.g. Article.objects.filter(~Q(id__iexact=self.id)) to exclude the current instance being edited from the list of related_articles a user can see and select from. Creation/setting of the queryset to use could occur within the constructor (__init__) of a custom Article ModelForm, or, via some kind of dynamic limit_choices_to Model option. This would require a way to grab the instance being edited to use for filtering.
Override the save_model function of the Article Model or ModelAdmin class to check for and remove itself from the related_articles before saving the instance. This still means that admin users can see and select all articles including the instance being edited (for existing articles).
Filter out self references when required for use outside the admin, e.g. templates.
The ideal solution (1) is currently possible to do via custom model forms outside of the admin as it's possible to pass in a filtered queryset variable for the instance being edited to the model form constructor. Question is, can you get at the Article instance, i.e. 'self' being edited the admin before the form is created to do the same thing.
It could be I am going about this the wrong way, but if your allowed to define a FKF / MTMF to the same model then there should be a way to have the admin - do the right thing - and prevent a user from selecting itself by excluding it in the list of available choices.
Note: Solution 2 and 3 are possible to do now and are provided to try and avoid getting these as answers, ideally i'd like to get an answer to solution 1.
Carl is correct, here's a cut and paste code sample that would go in admin.py
I find navigating the Django relationships can be tricky if you don't have a solid grasp, and a living example can be worth 1000 time more than a "go read this" (not that you don't need to understand what is happening).
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myManyToManyField'].queryset = MyModel.objects.exclude(
id__exact=self.instance.id)
You can use a custom ModelForm in the admin (by setting the "form" attribute of your ModelAdmin subclass). So you do it the same way in the admin as you would anywhere else.
You can also override the get_form method of the ModelAdmin like so:
def get_form(self, request, obj=None, **kwargs):
"""
Modify the fields in the form that are self-referential by
removing self instance from queryset
"""
form = super().get_form(request, obj=None, **kwargs)
# obj won't exist yet for create page
if obj:
# Finds fieldnames of related fields whose model is self
rmself_fields = [f.name for f in self.model._meta.get_fields() if (
f.concrete and f.is_relation and f.related_model is self.model)]
for fieldname in rmself_fields:
form.base_fields[fieldname]._queryset =
form.base_fields[fieldname]._queryset.exclude(id=obj.id)
return form
Note that this is a on-size-fits-all solution that automatically finds self-referencing model fields and removes self from all of them :-)
I like the solution of checking at save() time:
def save(self, *args, **kwargs):
# call full_clean() that in turn will call clean()
self.full_clean()
return super().save(*args, **kwargs)
def clean(self):
obj = self
parents = set()
while obj is not None:
if obj in parents:
raise ValidationError('Loop error', code='infinite_loop')
parents.add(obj)
obj = obj.parent