Finding Largest Value of an Integer Field - Django - python

I have a Django website and one of my models has an integer field. Does anyone know of a way to retrieve the largest value currently in that field into the view? Thanks!

I finally figured it out after about a week. Its close to a combination of both SELECT MAX and aggregation
models.py:
class Sheet_Building(models.Model):
user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT)
count_building = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True, verbose_name='Inspection Date')
time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time')
inspection_type = models.CharField(max_length=16, choices=INSPECTION_TYPE_BI, blank=True, null=True, verbose_name='Inspection Type')
flname = models.CharField(max_length=25, blank=True, null=True, verbose_name='Inspector')
report_date = models.DateField(blank=True, null=True, verbose_name='Report Date')
department = models.CharField(max_length=29, choices=DEPARTMENT_BI, blank=True, null=True, verbose_name='Department')
responsible_name = models.CharField(max_length=25, blank=True, null=True, verbose_name='Responsible Person')
building_address = models.CharField(max_length=52, choices=BUILDING_ADDRESS, blank=True, null=True, verbose_name='Building and Address')
floor = models.CharField(max_length=8, choices=FLOOR_LEVEL_BI, blank=True, null=True, verbose_name='Floor / Level')
room = models.CharField(max_length=35, blank=True, null=True, verbose_name='Area / Room')
location = models.CharField(max_length=10, choices=LOCATION_BI, blank=True, null=True, verbose_name='Location')
priority = models.IntegerField(blank=True, null=True, verbose_name='Priority')
hazard_level = models.CharField(max_length=20, choices=HAZARD_LEVEL_BI, blank=True, null=True, verbose_name='Hazard Level')
concern = models.CharField(max_length=31, choices=CONCERN_BI, blank=True, null=True, verbose_name='Concern')
codes = models.CharField(max_length=51, choices=CODES_BI, blank=True, null=True, verbose_name='Element and Code')
correction = models.TextField(max_length=160, blank=True, null=True, verbose_name='Corrective Action')
image = models.ImageField(blank=True, null=True, verbose_name='Image', upload_to='gallery')
notes = models.TextField(max_length=500, blank=True, null=True, verbose_name="Inspector's note")
class Meta:
ordering = ['-pk']
def __str__(self):
return self.flname or 'None'
def get_absolute_url(self):
return reverse('list_building')
view.py:
def adddata_building(response):
if response.method == 'POST':
form = SheetForm_Building(response.POST, response.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = response.user #User
if Sheet_Building.objects.filter(user=response.user).values_list('count_building'):
instance.count_building = Sheet_Building.objects.filter(user=response.user).aggregate(count_building=Max('count_building'))['count_building'] + 1 #Count
else:
instance.count_building = 1
instance.save()
response.user.Building.add(instance)
return redirect('list_building')
else:
form = SheetForm_Building()
return render(response, 'sheets/add_data/add_data_building.html', {'form': form})
HTML:
{% for post in object_list %}
{{ post.count_building }}
{% enfor %}

Related

Primary Key(count) for each user - Django

I have a Django website and part of it lists data in rows with the primary key in one of the columns. This works great except for when I have separate users. I'm using foreign keys in each model to separate the different user's data. My problem is that the data for each user has to have a number in the column that increments numerically and does not have any spacing, for instance, 1,2,3,5 is bad. If User1 is uploading data and halfway through User2 uploads a row of data then if I use the primary key the numbers will not be in numerical order for each user and will read 1,2,3,5 for User1 and 4 for User2. I tried forloop counter but I need the numbers all the be assigned to the row and not change if one is deleted. Ive been at this for 2 weeks and am having a really hard time describing my problem. I think I need somesort of Custom User Primary Key, a primary key for each user. Any help at this point is greatly appreciated, Thanks!
I finally figured it out after about a week.
models.py:
class Sheet_Building(models.Model):
user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT)
count_building = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True, verbose_name='Inspection Date')
time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time')
inspection_type = models.CharField(max_length=16, choices=INSPECTION_TYPE_BI, blank=True, null=True, verbose_name='Inspection Type')
flname = models.CharField(max_length=25, blank=True, null=True, verbose_name='Inspector')
report_date = models.DateField(blank=True, null=True, verbose_name='Report Date')
department = models.CharField(max_length=29, choices=DEPARTMENT_BI, blank=True, null=True, verbose_name='Department')
responsible_name = models.CharField(max_length=25, blank=True, null=True, verbose_name='Responsible Person')
building_address = models.CharField(max_length=52, choices=BUILDING_ADDRESS, blank=True, null=True, verbose_name='Building and Address')
floor = models.CharField(max_length=8, choices=FLOOR_LEVEL_BI, blank=True, null=True, verbose_name='Floor / Level')
room = models.CharField(max_length=35, blank=True, null=True, verbose_name='Area / Room')
location = models.CharField(max_length=10, choices=LOCATION_BI, blank=True, null=True, verbose_name='Location')
priority = models.IntegerField(blank=True, null=True, verbose_name='Priority')
hazard_level = models.CharField(max_length=20, choices=HAZARD_LEVEL_BI, blank=True, null=True, verbose_name='Hazard Level')
concern = models.CharField(max_length=31, choices=CONCERN_BI, blank=True, null=True, verbose_name='Concern')
codes = models.CharField(max_length=51, choices=CODES_BI, blank=True, null=True, verbose_name='Element and Code')
correction = models.TextField(max_length=160, blank=True, null=True, verbose_name='Corrective Action')
image = models.ImageField(blank=True, null=True, verbose_name='Image', upload_to='gallery')
notes = models.TextField(max_length=500, blank=True, null=True, verbose_name="Inspector's note")
class Meta:
ordering = ['-pk']
def __str__(self):
return self.flname or 'None'
def get_absolute_url(self):
return reverse('list_building')
view.py:
def adddata_building(response):
if response.method == 'POST':
form = SheetForm_Building(response.POST, response.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = response.user #User
if Sheet_Building.objects.filter(user=response.user).values_list('count_building'):
instance.count_building = Sheet_Building.objects.filter(user=response.user).aggregate(count_building=Max('count_building'))['count_building'] + 1 #Count
else:
instance.count_building = 1
instance.save()
response.user.Building.add(instance)
return redirect('list_building')
else:
form = SheetForm_Building()
return render(response, 'sheets/add_data/add_data_building.html', {'form': form})
HTML:
{% for post in object_list %}
{{ post.count_building }}
{% enfor %}

How to send id and slug in django Url?

I am trying to make django urls suitable for the seo. I want to send Id and slug in the same url.I don't want to use slug I only want to show in the url.But i am getting an error. My model looks like this:
class Oyunlar(models.Model):
game_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=10000)
platform = models.CharField(max_length=10)
image = models.CharField(max_length=255, blank=True, null=True)
release_date = models.DateField(blank=True, null=True)
click_count = models.IntegerField()
categories=models.ManyToManyField(Kategoriler,through='OyunlarKategoriler')
base_price=models.DecimalField(default=0,max_digits=65535, decimal_places=2)
big_discount=models.BooleanField(default=False)
en_ucuz = models.DecimalField(default=0,max_digits=65535, decimal_places=2)
popularite = models.IntegerField(blank=True, null=True,default=0)
discount_rate = models.DecimalField(max_digits=65535, decimal_places=2)
title_edit = models.CharField(max_length=500, blank=True, null=True)
description = models.CharField(max_length=100000, blank=True, null=True)
steam_id = models.CharField(max_length=1000, blank=True, null=True)
metacritic = models.FloatField(blank=True, null=True)
recommendation = models.BigIntegerField(blank=True, null=True)
full_game = models.BooleanField(blank=True, null=True)
age = models.CharField(max_length=500, blank=True, null=True)
minimum = models.CharField(max_length=10000, blank=True, null=True)
recommended = models.CharField(max_length=10000, blank=True, null=True)
developer = models.CharField(max_length=500, blank=True, null=True)
publisher = models.CharField(max_length=500, blank=True, null=True)
oyun_foto = ArrayField(models.CharField(max_length=10000, blank=True, null=True)) # This field type is a guess.
windows = models.BooleanField(blank=True, null=True)
mac = models.BooleanField(blank=True, null=True)
linux = models.BooleanField(blank=True, null=True)
class Meta:
managed = False
db_table = 'oyunlar'
def __str__(self):
return self.title
Urls.py
path('<int:game_id>/<slug:slug>/',views.oyun,name='detail'),
views.py
def oyun(request,slug,game_id):
print(slug)
oyun=Oyunlar.objects.get(pk=game_id)
comments=Comments.objects.filter(oyunlar=oyun)
game_price=GamePrice.objects.filter(game_id=game_id).order_by('price')
categories = OyunlarKategoriler.objects.filter(game=oyun).values_list('category_id', flat=True)
benzer = Oyunlar.objects.filter(categories__category_id__in=categories, platform=oyun.platform).order_by('-click_count').distinct()[:4]
print(request.method)
if request.method == 'POST':
cf = CommentForm(request.POST or None)
print('burda')
if cf.is_valid():
print('valid')
text = request.POST.get('text')
comment = Comments.objects.create(oyunlar=oyun, user=request.user, text=text)
comment.save()
return redirect(oyun.get_absolute_url())
else:
cf = CommentForm()
return render(request,'product-simple.html',{'oyun':oyun,'game_price':game_price,'benzer':benzer,'comment_form':cf,'comments':comments})
Helper Tag
#register.filter
def slug(value):
return slugify(unidecode(value))
html
<a href="{% url 'detail' i.game_id i.title|slug %}"
But I am getting an error:
Error
Reverse for 'detail' with arguments '(32147,)' not found. 1 pattern(s) tried: ['(?P<game_id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$']

Getting model filters to show count of active values

I have 2 models that are connected.
Model 1 is userprofiles and model 2 is events
each user can have multiple events... each event can be active or deactivated.
I have a for loop in the template showing all the userprofiles... but I also want to show how many active events each user has.
today = datetime.now().strftime('%Y-%m-%d')
perm = Permission.objects.get(codename='chef_user')
user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True).filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()[:6]
in the template I have my loop
{% for kitchen_list in user_profiles %}
-- CODE --
{{ kitchen_list.events_set.count }} <--- WHERE I AM TRYING TO SHOW ACTIVE EVENTS COUNT
--CODE--
{% endfor %}
my models:
class UserProfile(models.Model):
EVENT_TYPE = (('0', "Apartment"), ('1', "Home"),)
CURRENCY = (('R', "Rand"),)
OPTIONS = (('y', "Yes"),('n', "No"),)
OPTIONS_USER = (('y', "Yes"), ('n', "No"),('p', "Pending"),)
user = models.OneToOneField(User, related_name='profile')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(validators=[phone_regex], max_length=12, default='', blank=True) # validators should be a list
currency = models.CharField(max_length=50, blank=True, default='R', choices=CURRENCY)
bookingpermissions = models.CharField(max_length=100, blank=True, default='n', choices=OPTIONS)
title = models.CharField(max_length=50, default='', blank=True)
bio = models.TextField(max_length=500, default='', blank=True)
city = models.CharField(max_length=100, default='', blank=True)
longitude = models.CharField(max_length=100, default='na', blank=True)
latitude = models.CharField(max_length=100, default='na', blank=True)
image = ResizedImageField(size=[400, 400], crop=['middle', 'center'], upload_to='userprofile/static/images', default='', blank=True)
kitchen_type = models.CharField(max_length=50, blank=True, default='a', choices=EVENT_TYPE)
user_profile_active = models.CharField(max_length=1, default='n', blank=True, choices=OPTIONS_USER)
class Events(models.Model):
ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),)
ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing'))
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.CharField(max_length=1, default='b', choices=ACTIVE)
title = models.CharField(max_length=50, blank=True, default='')
description = models.TextField(max_length=500, blank=True, default='')
date = models.DateField()
time = models.TimeField()
price = models.CharField(max_length=240, blank=True, default='')
seats = models.IntegerField()
alcohol_choice = models.CharField(max_length=1, default='n' ,choices=ALCOHOL)
starter = models.TextField(max_length=350, blank=True, default='')
main_menu = models.TextField(max_length=350, blank=True, default='')
dessert = models.TextField(max_length=350, blank=True, default='')
notes = models.TextField(max_length=350, blank=True, default='')
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
you can try use model propery
in model:
class UserProfile(models.Model):
# You code here
#property
def active_events(self):
return self.user.events_set.filter(active='a').count()
in template:
{{ kitchen_list.userprofile.active_events }}
Rather do it in the views.py instead of the template to count then pass the values to the template. Assuming you hva e set up the foreign relations well in the models then in the views do the following:
user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True)
counts = user_profiles.events_set.count()
Then pass that as a context.
Or you can try creating a method in your model UserProfile:
class UserProfile:
....
def events(self):
return self.events_set.count()

Restrict form field choices based on previous model choice in Django

I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this:
I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand.
So far I have this:
models.py
class Race(models.Model):
race_name = models.CharField(max_length=200)
race_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M')
race_speed = models.IntegerField(
default=30)
race_lang = models.CharField(max_length=200, null=True, blank=True)
race_str = models.IntegerField(default=0, null=True, blank=True)
race_dex = models.IntegerField(default=0, null=True, blank=True)
race_con = models.IntegerField(default=0, null=True, blank=True)
race_int = models.IntegerField(default=0, null=True, blank=True)
race_wis = models.IntegerField(default=0, null=True, blank=True)
race_cha = models.IntegerField(default=0, null=True, blank=True)
skill_spend = models.IntegerField(default=0, null=True, blank=True)
race_extra = models.TextField(max_length=2000, blank=True, null=True)
race_source = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.race_name
class Meta:
verbose_name = 'Race'
verbose_name_plural = 'Races'
class Subrace(models.Model):
sub_name = models.CharField(max_length=200)
sub_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M', null=True)
sub_speed = models.IntegerField(
default=30, null=True)
sub_lang = models.CharField(max_length=200, null=True, blank=True)
sub_str = models.IntegerField(default=0, null=True, blank=True)
sub_dex = models.IntegerField(default=0, null=True, blank=True)
sub_con = models.IntegerField(default=0, null=True, blank=True)
sub_int = models.IntegerField(default=0, null=True, blank=True)
sub_wis = models.IntegerField(default=0, null=True, blank=True)
sub_cha = models.IntegerField(default=0, null=True, blank=True)
sub_extra = models.TextField(max_length=2000, null=True, blank=True)
sub_parent = models.ForeignKey(Race, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.sub_name
class Meta:
verbose_name = 'Subrace'
verbose_name_plural = 'Subraces'
class Hero(models.Model):
def roll_stats():
d6 = die.Dice(6)
list_stats = d6.roll(4)
list_stats.sort()
add = sum(list_stats[1:4])
return add
hero_name = models.CharField(max_length=200)
author = models.ForeignKey(User, null=True)
hero_subrace = models.ForeignKey(
Subrace, on_delete=models.CASCADE, null=True, blank=True)
pub_date = models.DateTimeField('date published', blank=True, null=True)
hero_klass = models.ForeignKey(Klass, on_delete=models.CASCADE, null=True)
hero_race = models.ForeignKey(Race, on_delete=models.CASCADE)
background = models.ForeignKey(
Background, on_delete=models.CASCADE, null=True)
health = models.IntegerField(blank=True, null=True)
hero_exp = models.IntegerField(default=0, null=True)
hero_alignment = models.ForeignKey(Alignment, blank=True, null=True)
hero_str = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_dex = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_con = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_int = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_wis = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_cha = models.IntegerField(default=roll_stats, null=True, blank=True)
def save(self, *args, **kwargs):
"Returns a hero's hp"
die_str = str(self.hero_klass.hit_dice)
die_nums = die_str.split("d")
die_val = int(die_nums[1])
die_roll = int(die_nums[0])
hp_die = die.Dice(die_val)
results = hp_die.roll(die_roll)
self.health = sum(results)
super(Hero, self).save(*args, **kwargs)
def __str__(self):
return self.hero_name
def get_absolute_url(self):
return reverse('hero.views.detail', args=[str(self.id)])
class Meta:
verbose_name = 'Hero'
verbose_name_plural = 'Heroes'
views.py
def new_hero(request):
user = request.user
if request.method == "POST":
form = HeroForm(request.POST)
if form.is_valid():
hero = form.save(commit=False)
hero.author = request.user
hero.save()
return redirect('detail', hero.pk)
else:
form = HeroForm()
return render(request, 'new_hero.html', {'form': form, 'user': user})
forms.py
class HeroForm(forms.ModelForm):
class Meta:
model = Hero
fields = ['hero_name', 'hero_race', 'hero_subrace',
'hero_klass', 'hero_exp', 'health', 'background',
'hero_str', 'hero_dex', 'hero_con', 'hero_int',
'hero_wis', 'hero_cha', 'hero_alignment']
def __init__(self, *args, **kwargs):
super(HeroForm, self).__init__(*args, **kwargs)
for fieldname in ['hero_str', 'hero_dex', 'hero_con', 'hero_int', 'hero_wis', 'hero_cha']:
self.fields[fieldname].disabled = True
race = Race.objects.all()
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
I have trialled a few different techniques, but this is where I am now. This:
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
is my most recent addition to my app. At the hero creation screen I am hit with a blank box of choices, as opposed to the full unrestricted list without the loop or queryset.
Basically I'm hoping that someone has some advice for me on a method I may be overlooking, or something that I've missed, or simply not found yet. Also please feel free to critique the rest of the code, like I said this is my first Django App :). Also my first Stack Overflow question, so thanks :)
For anyone that is wondering, I used django-smart-selects to solve my problem.
base.html
<script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
<script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script>
I added the above html to my {% load staticfiles %} call.
and changed models.py:
models.py
from smart_selects.db_fields import ChainedForeignKey
class Hero(models.Model):
....
race = models.ForeignKey(Race, on_delete=models.CASCADE)
subrace = ChainedForeignKey(Subrace,
chained_field="race",
chained_model_field="race",
show_all=False,
auto_choose=True,
blank=True,
null=True)
Now I have a subrace field that is dynamically update when the user chooses a Race.

Django planmember_set issue

I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function:
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"])
return owners
Only problem is that I get an output of:
[<PlanMember: Doe, John (Primary)>, <PlanMember: Doe, Jane(Joint Subscriber)>, etc]
Now is there a way for me to just show their names and the member type (the words in brackets)?
A bit of background code.
Here is my views.py:
if request.POST:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p), request.POST)
if form.is_valid():
selected_plan = form.cleaned_data['plans']
plan = get_object_or_404(Plan, pk=selected_plan.pk)
investment_list = Investment.objects.all().filter(Q(plan = plan)).order_by('maturity_date')
context['investment_list'] = investment_list
context['plan'] = plan
context['today'] = now
context['current_yr'] = current_year
context['next_yr'] = next_year
context['show_report'] = True
else:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p))
context['form'] = form
return render_to_response('reports/planmaturities_year.html', RequestContext(request, context))
And my forms.py:
class PlanMaturityYearForm(forms.Form):
def __init__(self, plans, *args, **kwargs):
super(PlanMaturityYearForm, self).__init__(*args, **kwargs)
self.fields['plans'] = forms.ModelChoiceField(
plans,
required=True,
widget=forms.Select(attrs={'size': 20}),
error_messages={'required':'Please select the plan you wish to build the report for',}
)
Edit:
models.py
class Plan(models.Model):
old_id = models.IntegerField(null=True)
closed = models.BooleanField(default=False, blank=True)
closed_date = models.DateField(null=True)
profile = models.ForeignKey(Profile, default=False)
plan_type = models.ForeignKey(PlanType)
ownership_type = models.ForeignKey(OwnershipType)
status = models.PositiveSmallIntegerField(max_length=2, default=PLAN_OPEN)
timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True)
notes = HTMLField(blank=True, null=True)
bank = models.CharField(max_length=50, blank=True, null=True)
account = models.CharField(max_length=50, blank=True, null=True)
transit = models.CharField(max_length=50, blank=True, null=True)
objects = PlanManager()
class Profile(models.Model):
old_id = models.IntegerField(null=True, blank=True)
label = models.CharField(max_length=255, blank=True, verbose_name='Profile label/description')
location = models.ForeignKey(Location, null=True, blank=True)
client = models.BooleanField(default=False, blank=True)
corp = models.BooleanField(default=False, blank=True)
noncorp = models.BooleanField(default=False, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, default=False)
bak_agent_id = models.CharField(max_length=10, null=True, blank=True)
agent = models.ForeignKey(Agent, related_name='profiles')
check1 = models.BooleanField(default=False, blank=True)
incorp_date = models.DateField(null=True, blank=True)
corp_records = models.BooleanField(default=False, blank=True)
articles_of_incorp = models.BooleanField(default=False, blank=True)
other_corp_articles = models.CharField(max_length=50, null=True, blank=True)
bin = models.CharField(max_length=50, null=True, blank=True, verbose_name='BIN')
phone = models.CharField(max_length=25, null=True)
registration = models.CharField(max_length=45, null=True, blank=True)
num_sigs = models.IntegerField(max_length=1, null=True, blank=True,
verbose_name='Number of signatures required to transaction the account')
charity = models.BooleanField(default=False, blank=True)
donations_solicited = models.BooleanField(default=False, blank=True)
ownership_type = models.CharField(max_length=45, null=True, blank=True)
ownership_other = models.CharField(max_length=45, null=True, blank=True) #work around for other business type selction
business_nature = models.CharField(max_length=45, null=True, blank=True)
date_incept = models.DateField(null=True, blank=True)
bind_power = models.BooleanField(default=False, blank=True)
reg_documents = models.BooleanField(default=False, blank=True)
other_documents = models.CharField(max_length=50, null=True, blank=True)
reg_number = models.CharField(max_length=45, null=True, blank=True)
tax_number = models.CharField(max_length=45, null=True, blank=True)
phone = models.CharField(max_length=25, null=True, blank=True)
fax = models.CharField(max_length=25, null=True, blank=True)
email = models.CharField(max_length=100, null=True, blank=True)
You can use values_list:
owners = self.planmember_set.filter(
ownership_type__code__in=["primary","joint"]
).values_list('name', 'type')
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"]).values_list('name_field', 'ownership_type__code')
return owners
Write where and how you use get_owners if not correct.

Categories

Resources