Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I grab the (text) value instead of the number on a multiple choice field?
I have a CreateView class and I'm trying to use the input from a multiple choice field it has as part of the success_url. It works on my TopicCreateView class because the input is a charfield, but when I try to get it to work on PostCreateView it returns a KeyError. From what i understand it's because it returns the value of the multiple choice field(1, 2, 3 etc) instead of the text between the option tags. The Topic part works fine. views.py class TopicCreateView(LoginRequiredMixin, CreateView): model = Topic template_name = 'topic_form.html' fields = ['board', 'title'] success_url = '/topic/{title}' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) And here is the models.py class Topic(models.Model): title = models.CharField(max_length=100, unique=True) board = models.ForeignKey(Board, default='ETC', on_delete=models.SET_DEFAULT) date_published = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Here is what I can't get to work, the Post. views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'post_form.html' fields = ['topic', 'content'] success_url = '/topic/{topic}' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and models.py class Post(models.Model): content = models.TextField() author = models.CharField(max_length=200, default='Unknown', blank=True, null=True) date_published = models.DateTimeField(default=timezone.now) topic = models.ForeignKey(Topic, default=content, on_delete=models.SET_DEFAULT) def __str__(self): return self.topic So, when I redirect to the newly created topic/thread it … -
filling two table with one post request
I have a model that stores a text. I have another related model that is supposed to store the entities in the first model. For example suppose I am posting a text like "France is in Europe", which will go in News model, and then once this string is posted, the Entity model should store two rows Frence and Europe. How could I achieve this once the string is posted? Here is my models and serializes: class News(models.Model): description = models.TextField(verbose_name="Description", max_length=50, blank=True, null=True, default="") timestamp = models.DateTimeField(auto_now_add=True) class Entity(models.Model): news = models.ForeignKey( News, related_name='entities4thisnews', on_delete=models.CASCADE) entity = models.TextField(verbose_name="Entity", max_length=100, blank=True, null=True, default="") timestamp = models.DateTimeField(auto_now_add=True) class EntitySerializer(serializers.HyperlinkedModelSerializer): news = serializers.SlugRelatedField(queryset=News.objects.all(), slug_field='pk', ) class Meta: model = Entity fields = ('url', "id", 'news', 'entity', 'timestamp', ) class NewsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = News entities4thisnews = EntitySerializer(many=True, required=False) fields = ( "url", "id", "description", 'timestamp', 'entities4thisnews', ) My guess is that I should add some code in perform_create() but not quite sure how. here is my views.py: class NewsList(generics.ListCreateAPIView): queryset = News.objects.all() serializer_class = NewsSerializer name = 'news-list' def perform_create(self, serializer): pass class EntityList(generics.ListCreateAPIView): queryset = Entity.objects.all() serializer_class = EntitySerializer name = 'entity-list' -
I need to create a web app that takes takes in a text submission box, manipulating the response/input to provide output on the screen
I need to create a web app that has a text box, the page contains an input field, after receiving input, it displays what was input back to the user. I really just need help thinking through the tech stack. I'd love to bootstrap it because I've never used React before, but heard that was the best starting point. No code yet!!! -
Python# How to list all classes in a project which inherit another class?
How to list all classes in a project which inherit another class? -
Is there any way in django to distinguish if it is a normal browser request or ajax request
I am using django and making some ajax request to server. As the url is visible in javascript someone could easily copy that and start making request via url bar. Is there any way in django that we can distinguish that the coming request is sent by ajax not a regular browser reqeust. -
TypeError at /sendmail/
send_mail() missing 1 required positional argument: 'recipient_list' In seetings.py I added these lines as a setup to send an email EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'jshrijit@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True EMAIL_USE_SSL = False Then in views.py I created the function to send an email def index(request): send_mail( 'Hello from sender', 'Hey, how are you?.' 'from@gmail.com', ['to@gmail.com'], fail_silently=False, ) and I got below error Exception Type: TypeError Exception Value: send_mail() missing 1 required positional argument: 'recipient_list' Please help me regarding this..... -
I need to Override the default rest auth login serializer and views to my customer abstract user model
I tried overriding the django rest auth login serializer to suit my custom user model. but i cannot get the JWT token I Overided the path to my custom serializer in my Accounts app, i'm not really clear with the code. i need help in writing a customer userlogin and register serializer and to return the token to my frontend #setttings.py REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER':'accounts.serializers.UserLoginSerializer', 'TOKEN_SERIALIZER': 'rest_auth.serializers.TokenSerializer', 'USER_DETAILS_SERIALIZER':'accounts.serializers.UserDetailSerializer', } #serializers.py class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = { 'password': {'write_only':True} } def validate_email(self, value): qs = User.objects.filter(email__iexact = value) if qs.exists(): raise serializers.ValidationError('Email already exist please pick another one') return value # def validate_email(self, data): # user_obj = None # email = data.get('email', None) # password = data['password'] # if not email : # raise ValidationError('Email is recquired to login') # user = User.objects.filter( # q(email = email) # ).distinct() # user = user.exclude(email__isnull = True) # if user.exists() and user.counts() == 1: # user = user.first # else : # raise ValidationError("This Email Is not Valid") # if user_obj: # if not user_obj.check_password(password): # raise ValidationError('Incorrect credentials check password') # data["token"] # return data i expected it to return the JWT … -
How to fix 'The QuerySet value for an exact lookup must be limited to one result using slicing.' error in Django
I'm trying to return the count of a filtered qweryset in my Django views. How do I achieve this while avoiding the 'The QuerySet value for an exact lookup must be limited to one result using slicing.' error? I've tried to use len() but I still arrive at the same error. This is my code: models class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) read_time = models.CharField(max_length=256, null=True, blank=True) count_visits = models.IntegerField(default=0) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:blog_post', args=[self.slug]) def get_body_as_markdown(self): return mark_safe(markdown(self.body, safe_mode='escape')) class PostView(models.Model): post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True, related_name='postviews') ip = models.CharField(max_length=50) http_host = models.CharField(max_length=256, null=True, blank=True) http_referrer = models.CharField(max_length=256, null=True, blank=True) http_user_agent = models.CharField(max_length=256, null=True, blank=True) remote_host = models.CharField(max_length=256, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.ip views: class PostDetailView(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get(self, request, *args, **kwargs): self.slug = get_object_or_404(Post, slug=self.kwargs['slug']) p = Post.objects.filter(slug=self.slug) count_visits = None unique_views = set() if self.request.user.is_authenticated: post_views … -
Is there any non-trivial library for reducing boilerplate in Django CRUD apps?
I've been working with web2py during the last time, but for my new web application I want to experiment with Django. However, I've found that trivial CRUD forms require a lot of boilerplate. I understand that generic views give me all the logic for input to or output from a model, but I still have to do heavy HTML work and add my own logic to support filters, ordering, pagination, etc. For example, in web2py I can just use the following code (consider it as the function-based view in Django's world) to get a feature-rich and highly-customizable CRUD view. def manage_users(): grid = SQLFORM.grid(db.users) return {"grid": grid} Is there any de-facto way (apart from the admin application) or library you Django folks use to reduce the boilterplate of writing ~200 lines of code to achieve the same thing that web2py gives you for free? Note: this is not a web2py vs. Django question. I understand they propose different philosophies and that Django is much more flexible than web2py, while web2py gives you more features out of the box. I'm just asking how is this resolved in the Django world. Thanks in advance guys! -
Building a ranking system on Django
I have a Django soccer app with following models and I want to make a queryset (or something else) to build a "ranking" table on my template (pass as context): Round (round_number, round_name) Game (round, team1, team2, goals, faults) Team (name) Player (name, team) Goal (game, player) Fault (game, player) Having these models with these fields, how can I build a ranking table with following information? Team | Wins | Losses | Games Played -
Django - models - number of fields not known in advance
Sorry if the answer is obvious, but I am building an django app about poetry. In my models, I have a class Verse, and I would like to have Hemistich in it. However, depending on the poem, it can be 2,3 or 4 of them so I can’t set the number in advance. Any idea how I can implement that ? Thank you. -
Django query: all users with the given email
Can this be written more elegantly in Django? User.objects.filter(pk__in=EmailContact.objects.filter(email=email).values_list('user__pk', flat=True)) I want to fetch all users with the given email address through the EmailContact table. User has a emailcontact_set, if that helps. Thank you. -
Allow anonymous user to view page
I want to change existing site so non registered users can view it. Everyone can access list of products (wagtail parent page). But when I want to access individual product error appear: 'AnonymousUser' object is not iterable I think the problem is in my product/models.py I will show complete code so someone please help. from itertools import chain from random import shuffle from django.contrib import messages from django.db import models from django.conf import settings from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey from taggit.models import TaggedItemBase from wagtail.api import APIField from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailimages.models import Image from wagtail.wagtailsearch import index from wagtail.wagtailsnippets.models import register_snippet from djmoney.models.fields import MoneyField from category.models import Category from courtesy_of.models import CourtesyOf from reggie_market.core.views import products_context from reggie_market.core.models import TimeStampedModel, ExtraContextMixin from users.models import add_wishlist class ProductCategory(Orderable, models.Model): category = ParentalKey(Category, related_name='related_products') product = ParentalKey('product.Product', related_name='related_categories') panels = [ FieldPanel('category'), FieldPanel('product'), ] class ProductIndex(ExtraContextMixin, Page): subpage_types = ('product.Product', 'product.ProductIndex', 'category.Category',) @property def child_pages(self): return Product.objects.live().child_of(self) @property def products(self): products = Product.objects.filter(is_user_mode=False) products = products.select_related( 'owner', 'image', ).order_by('-created') return products def get_context(self, request, courtesy_of=None, *args, **kwargs): context = super(ProductIndex, self).get_context(request, *args, … -
I want to update the content using jquery and ajax. I want to apply summernote on this
I want to update the content using jquery and ajax. I want to apply summernote on this. I am updating using textarea now there is a problem. What you need to update Because it is shown as a tag It is difficult to modify it I do not know how. In the case of textarea 1.html tag <textarea name="name" rows="10" cols="110" id="my_code_{{comment.id}}" class="todo_comment_text_{{comment.id}}" hidden>{{comment.text}}</textarea> Update with Jquery $(".comment_edit_button").click(function(e) { e.preventDefault(); var id = $(this).attr("id"); var title = $("#todo_comment_title_"+id).val(); var file_name = $("#todo_comment_file_name_"+id).val(); var text = $(".todo_comment_text_"+id).val(); $.ajax({ type: "POST", url: 'update_comment_ajax/'+id, data: { id:id, title:title, file_name:file_name, text:text, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { alert("modify is completted") $(".comment_edit_form_button").attr("hidden",true); } }); }); Is it possible to use summernote's input window the same way? -
Django filter on generic relationship (unique constraint exception)
I have a model below which points to a generic relationship. This can either be a Post object or a Reply object. class ReportedContent(models.Model): reporter = models.ForeignKey(User, on_delete=models.CASCADE) # Generic relation for posts and replies content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: unique_together = ('reporter', 'object_id', 'content_type') I would like to check if the content_object is already exists before I get a duplicate key value violates unique constraint exception. Django documentation mentioned that: # This will fail >>> ReportedContent.objects.filter(content_object=content) # This will also fail >>> ReportedContent.objects.get(content_object=content) So how can I filter on generic relation? or how can I deal with this exception specifically? -
How to skip different amounts of rows on excel files while reading them with a loop?
I have some old code that grabs specific files and opens each one individually. Come to find out, it is much better to load the files from the objects that were created when uploading. How to skip different amount of rows on different files while looping to open them? I have tried to search for this but it does not seem like a common issue. Currently the files load like this: # place uploaded files into variables sar = 'media/'+current_user+'/Stylist_Analysis.xls' sar2 = 'media/'+current_user+'/Stylist_Analysis.xls' tips = 'media/'+current_user+'/Tips_By_Employee_Report.xls' hours_wk1 = 'media/'+current_user+'/Employee_Hours1.xls' hours_wk2 = 'media/'+current_user+'/Employee_Hours2.xls' retention = 'media/'+current_user+'/SC_Client_Retention_Report.xls' efficiency = 'media/'+current_user+'/Employee_Service_Efficiency.xls' # begin processing payroll df_sar = pd.read_excel( sar, sheet_name=0, header=None, skiprows=4) df_sar2 = pd.read_excel( sar2, sheet_name=0, header=None, skiprows=4) df_tips = pd.read_excel( tips, sheet_name=0, header=None, skiprows=0) df_hours1 = pd.read_excel( hours_wk1, header=None, skiprows=5) df_hours2 = pd.read_excel( hours_wk2, header=None, skiprows=5) df_retention = pd.read_excel( retention, sheet_name=0, header=None, skiprows=8) df_efficiency = pd.read_excel( efficiency, sheet_name=0, header=None, skiprows=5) I would like to load the files using the Django objects like this: for report in request.user.uploadreports_set.all(): content = report.xls.read() ... The problem being that each file needs different amount of skiprows=x. Is there a way to do this during load or should I just read the files then skip the … -
How to access a field name in Django model via the verbose name
I have the verbose name of a model and I would like to get the corresponding field name. I'm able to access all the field names by using _meta..., but I only want to access a particular field name based on the verbose name. I would like to plug in the verbose name and get back what the field name is. All the examples that I've found you can only enter the field name in the Model._meta.get_field('fieldname') and not the verbose name to get whatever the field name is. res = Model._meta.get_field('test_field').verbose_name res returns 'Test Field' res = Model._meta.get_field('test_field').name res returns 'test_field' If I enter the verbose name for ex: res = Model._meta.get_field('Test Field').name I get an error raise FieldDoesNotExist KeyError" 'Test Field' I would like the output to be the field name 'test_field' -
Data in table is not updated from django-rest-framework UpdateAPIView?
This is my update api view: class CountlUpdateView(UpdateAPIView): serializer_class = CountSerializers def get_queryset(self, *args, **kwargs): id = self.kwargs.get('pk') queryset = Count.objects.filter(pk=id) return queryset this is urls path path('count/<int:pk>/update/', CountlUpdateView.as_view()), This is my serializer class: class CountSerializers(serializers.ModelSerializer): class Meta: model = Count fields = ('id', 'userId', 'channelId', 'rate') When I hit my urls I got my rest framework update view form with put method. I update the field and click on put. Then I got the following message HTTP 200 OK Allow: PUT, PATCH, OPTIONS Content-Type: application/json Vary: Accept { "id": 1, "userId": 4, "channelId": 10, "rate": 10 } This is a correct update from my end. But when I check in the database then I found the old value and the data is not updated in the database. What should I do so that data is updated in my database? -
djangocms error cms_urlconfrevision on deployment
i'm trying to deploy a djangocms app to pythonanywhere or heroku but i keep getting this error on heroku ProgrammingError at / relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... and this error on pythonanywhere OperationalError at / no such table: cms_urlconfrevision the app works fine on localhost . i understand it's a db table missing but i have no idea how to fix it i tried removing all the migration files and pyc and migrated again , i removed the db tried migration --fake . nothing seems to work . i'm using django-cms==3.6.0 and Django==2.1.8 -
How to dynamically load data into Django template
I am trying to load data dynamically into a django template using a bootstrap modal. What I am doing right now works: def showprofile(full_name): return mentee.objects.filter(full_name="Katha Benterman") But I want to dynamically be able to load the data, I posted an earlier question which I have tried but does not work on my end: How to display model fuction in Django template When I try this code which is within my model: def showprofile(self,full_name): return self.objects.filter(full_name=fullname) I get this error showprofile() missing 1 required positional argument: 'full_name' I am but confused because when I try to pass self it says self is not defined. A bit confused as to what is going on any help would be appricated! This is how the view looks like: def home(request): if request.method == 'GET': data = mentee.objects.all() profiles = mentee.showprofile(mentee.full_name, mentee.full_name) mentee_data = { "full_name": data, "email": data, "email": data, "phone" : data, "bio" : data, "gender" : data, "objectives" : data, "years_of_experience" : data, "university" : data, "graduation_year" : data, "major" : data, "class_standing" : data, "city" : data, "country" : data, "student_type" : data, "profile_pic" : data, "linkedin" : data, "GitHub" : data, "website" : data, "resume" : data, "area_of_concentration" : … -
Django-tinymce not loading on Amazon S3 despite all other static files loading
I've been using this guide https://www.codingforentrepreneurs.com/blog/s3-static-media-files-for-django/ to get to use S3 for my site's static files. I had TinyMCE working locally, but once I started using S3 to for my files it's the only part that won't load and the widgets that use it simply don't appear. In the Chrome Dev Tools console, I am getting the following error: Failed to load resource: the server responded with a status of 403 (Forbidden) tiny_mce.js?AWSAccessKeyId=AKIAUQEKDYTXEMAYFQ4L&Signature=Ze0U3pre28m%2FD9x2ftvTQkXl0OI%3D&Expires=1558648014:1 Failed to load: https://conucos-bucket.s3.amazonaws.com/static/assets/js/tiny_mce/plugins/autosave/editor_plugin.js On S3 I've made all files public in the Bucket Public and get Access Denied for 2 files in TinyMCE static/assets/js/tiny_mce/plugins/media/langs/dv_dlg.js /conucos-bucket/ static/assets/js/tiny_mce/plugins/searchreplace/langs/mk_dlg.js /conucos-bucket/ And the rest are successful. The following is my configuration file which I import in settings.py import datetime AWS_GROUP_NAME = #REDACTED AWS_USERNAME = #REDACTED AWS_ACCESS_KEY_ID = #REDACTED AWS_SECRET_ACCESS_KEY = #REDACTED AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'conucos.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'conucos.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'conucos-bucket' S3DIRECT_REGION = 'us-east-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), … -
Data is not updated in database from django Rest framework update view?
This is my serializer class: class CountSerializers(serializers.ModelSerializer): class Meta: model = Count fields = ('id', 'userId', 'channelId', 'rate') This is my update view: class CountlUpdateView(UpdateAPIView): serializer_class = CountSerializers def get_queryset(self, *args, **kwargs): id = self.kwargs.get('pk') queryset = Count.objects.filter(pk=id) return queryset And this is my urls path path('count/<int:pk>/update/', CountlUpdateView.as_view()), When I hit my urls I got my rest framework update view form with put method. I update the field and click on put. Then I got the following message HTTP 200 OK Allow: PUT, PATCH, OPTIONS Content-Type: application/json Vary: Accept { "id": 1, "userId": 4, "channelId": 10, "rate": 10 } This is a correct update from my end. But when I check in the database then I found the old value and the data is not updated in the database. What should I do so that data is updated in my database? -
How to add and convert the Django template language from the bootstrapstudio at the time of exporting using Beautiful soup?
I am designing webpages using BootstrapStudio + Django. I want to know how to insert the Django template language at the time of exporting BSS to actual html site using Beautifulsoup? This will immensely help me to redesign site whenever i want, with less amount of time. Actual code in HTML: <div class="item" dj-for="i in items"> <h2 dj-ref="i.name">This is the heading</h2> <div dj-ref="i.content|markdown">Lorem ipsum dolor sit amet …</div> </div> Need to be converted as: {% for i in items %} <div class="item"> <h2>{{ i.name }}</h2> <div>{{ i.content|markdown }}</div> </div> {% endfor %} For more detailed understanding of the question, plz visit the following link: https://bootstrapstudio.io/forums/topic/use-with-django/ -
Should a celery task save django model updates immediately?
I have a celery task that runs for five minutes at a time to check an azure service bus subscription topic for messages. Throughout the five minutes, it pings the service bus every second to check for a message, and if it finds one, it saves some info to a database. I`ve noticed that the actual commit to the database only occurs when the task ends at the five minute mark, and not when the model.save() method is called. I'm wondering, is it a good idea to add some code to force each save to occur immediately, instead of at the end of the five minutes? I`m thinking of using a statement that involves atomic transactions to accomplish this. The code below contains my task. I use a while loop to keep the task going for 5 minutes, and inside it, I ping the service bus for messages every second, and then save them if found. class CheckForUpdates(PeriodicTask): run_every = 300 def run(self, queue_name='bus_queue'): end_task_time = _at_five_minutes() while time.time() < end_task_time: _wait_for_one_second() result = _check_service_bus_for_update() if _update_was_found(result): update = json.loads(result.body) logger.info("azure response body: ", update) # code that updates a django model model.save() Is this a good design? It is … -
Find duplicates based on grandparent-instance id and remove older one based on timestamp field
I’m trying to find grandchildren objects of the same instance in a Django queryset and filter out grandchildren instances with older timestamps. I suppose I could do this with distinct(*specify_fields) function, but I don’t use Postgresql database (docs). I managed to achieve this with the following code: queryset = MyModel.objects.filter(some_filtering…) \ .only('parent_id__grandparent_id', 'timestamp' 'regular_fields'...) \ .values('parent_id__grandparent_id', 'timestamp' 'regular_fields'...) # compare_all_combinations_and_remove_duplicates_with_older_timestamps list_of_dicts = list(queryset) for a, b in itertools.combinations(list_of_dicts, 2): if a['parent_id__grandparent_id']: == b['parent_id__grandparent_id']: if a['timestamp'] > b['timestamp']: list_of_dicts.remove(b) else: list_of_dicts.remove(a) However, this feels hacky and I guess this is not an optimal solution. Is there a better way (by better I mean more optimal, i.e. minimizing the number of times querysets are evaluated etc.)? Can I do the same with queryset’s methods? My models look something like this: class MyModel(models.Model): parent_id = models.ForeignKey('Parent'… timestamp = … regular_fields = … class Parent(models.Model): grandparent_id = models.ForeignKey('Grandparent'… class Grandparent(models.Model): …