Django model field default based on another model field

2024/9/21 1:26:27

I use Django Admin to build a management site. There are two tables, one is ModelA with data in it, another is ModelB with nothing in it. If one model field b_b in ModelB is None, it can be displayed on the webpage with the value of ModelA's field a_b.

I don't know how to do it, Here is the pseudo code:

In models.py

from django.db import modelsclass ModelA(models.Model):a_a = models.CharField(max_length=6)a_b = models.CharField(max_length=6)class ModelB(models.Model):modela = models.OneToOneField(ModelA)b_b = models.CharField(max_length=6, choices=[(1, 'M'), (2, 'F')], default=self.modela.a_b)

In admin.py

from django.contrib import admin
from .models import ModelA, ModelBclass ModelBAdmin(admin.ModelAdmin):fields = ['b_b']list_display = ('b_b')

I think if b_b of modelB have default value of relative a_b value of modelA, I have a default value of b_b(View) in the django admin change(edit) page which associate data to a particular modelB instance.

I want to fill b_b in web page more easily.

I don't know whether this requirement can be achieved? Or there is another way can achieve this?

I try to custom the templates filter as following:

In templates/admin/includes/fieldset.html

 {% load drop_null %}{% if field.is_checkbox %}{{ field.field }}{{ field.label_tag }}{% else %}{{ field.label_tag }}{% if field.is_readonly %}<p>{{ field.contents }}</p>{% else %}{% if field.field.name == 'b_b' %}{{ field|dropnull }}{% else %}{{ field.field }}{% endif %}{% endif %}{% endif %}

In templatetags/drop_null.py

from django import template
register = template.Library()@register.filter(name='dropnull')
def dropnull(cls):return cls.modela.a_b

The 'field' is < django.contrib.admin.helpers.AdminField object at 0x3cc3550> . It is not an instance of ModelB. How can I get ModelB instance?

Answer

You can override the save method of your modelB model instead of providing a default value:

class ModelB(models.Model):modela = models.OneToOneField(ModelA)b_b = models.CharField(max_length=6, choices=[(1, 'M'), (2, 'F')], blank=True)def save(self, *args, **kwargs):if not self.b_b:self.b_b = self.modela.a_bsuper(ModelB, self).save(*args, **kwargs)

Edit after clarification in the comments

If you just want to display the value to visitors but want to keep the fact that the ModelB.b_b is empty, the logic should lay in the template.

Assuming your view set objB in the context being the ModelB object your are interested to display, the relevant part of the template should look like:

{% with objB.b_b as bValue %}
{% if not bValue %}<p>{{ objB.modela.a_b }}</p>
{% else %}<p>{{ bValue }}</p>
{% endif %}
{% endwith %}
https://en.xdnf.cn/q/72434.html

Related Q&A

How do I improve remove duplicate algorithm?

My interview question was that I need to return the length of an array that removed duplicates but we can leave at most 2 duplicates. For example, [1, 1, 1, 2, 2, 3] the new array would be [1, 1, 2, 2,…

Looking for values in nested tuple

Say I have:t = ((dog, Dog),(cat, Cat),(fish, Fish), )And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not m…

Multiple lines user input in command-line Python application

Is there any easy way to handle multiple lines user input in command-line Python application?I was looking for an answer without any result, because I dont want to:read data from a file (I know, its t…

Performance difference between filling existing numpy array and creating a new one

In iterative algorithms, it is common to use large numpy arrays many times. Frequently the arrays need to be manually "reset" on each iteration. Is there a performance difference between fill…

Set space between boxplots in Python Graphs generated nested box plots with Seaborn?

I am trying to set a space between the boxplots (between the green and orange boxes) created with Python Seaborn modules sns.boxplot(). Please see attached the graph, that the green and orange subplot …

Geocoding using Geopy and Python

I am trying to Geocode a CSV file that contains the name of the location and a parsed out address which includes Address number, Street name, city, zip, country. I want to use GEOPY and ArcGIS Geocodes…

Making Python scripts work with xargs

What would be the process of making my Python scripts work well with xargs? For instance, I would like the following command to work through each line of text file, and execute an arbitrary command:c…

TypeError: expected string or buffer in Google App Engines Python

I want to show the content of an object using the following code:def get(self):url="https://www.googleapis.com/language/translate/v2?key=MY-BILLING-KEY&q=hello&source=en&target=ja&quo…

Returning a row from a CSV, if specified value within the row matches condition

Ahoy, Im writing a Python script to filter some large CSV files.I only want to keep rows which meet my criteria.My input is a CSV file in the following formatLocus Total_Depth Average_Depth_sa…

Python multiprocessing pool: dynamically set number of processes during execution of tasks

We submit large CPU intensive jobs in Python 2.7 (that consist of many independent parallel processes) on our development machine which last for days at a time. The responsiveness of the machine slows …