How to send id and slug in django Url? - python

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_]+)/$']

Related

How to filter Many to Many field in django admin page using a foreign key value?

I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value

Finding Largest Value of an Integer Field - Django

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 %}

Getting a POST request to act like a GET request? djangorestframework-datatables

I don't want to add data to the database, like what djangorestframework-datatables is trying to do with the POST request. I need to use a POST request instead of a GET request because the URI for the GET request is too long (I had to change nginx and gunicorn limits on the production server, to unlimited length (max wasn't enough) which opens the site up to ddos attacks, which is obviously not ideal.
Here is the code:
# api/serializers
class ReportSerializer(serializers.ModelSerializer):
class Meta:
model = Report
fields = "__all__"
# api/views
class ReportViewSet(viewsets.ModelViewSet):
queryset = Report.objects.all()
serializer_class = ReportSerializer
# reports/models
class Report(models.Model):
contribution_expenditure_type = models.CharField(max_length=255, choices=CONTRIBUTION_EXPENDITURE_TYPES)
filer_id = models.BigIntegerField()
filer_namL = models.CharField(max_length=255)
report_num = models.CharField(max_length=255)
committee_type = models.CharField(max_length=255)
rpt_date = models.CharField(max_length=255)
from_date = models.CharField(max_length=255)
thru_date = models.CharField(max_length=255)
elect_date = models.CharField(max_length=255)
rec_type = models.CharField(max_length=255)
form_type = models.CharField(max_length=255, blank=True, null=True)
tran_id = models.CharField(max_length=255, blank=True, null=True)
entity_cd = models.CharField(max_length=255, blank=True, null=True)
tran_namL = models.CharField(max_length=255)
tran_namF = models.CharField(max_length=255, blank=True, null=True)
tran_city = models.CharField(max_length=255, blank=True, null=True)
tran_state = models.CharField(max_length=255, blank=True, null=True)
tran_zip4 = models.CharField(max_length=255, blank=True, null=True)
tran_emp = models.CharField(max_length=255, blank=True, null=True)
tran_occ = models.CharField(max_length=255, blank=True, null=True)
tran_self = models.CharField(max_length=255, blank=True, null=True)
tran_type = models.CharField(max_length=255, blank=True, null=True)
tran_date = models.CharField(max_length=255)
tran_date1 = models.CharField(max_length=255, blank=True, null=True)
tran_amt1 = models.DecimalField(max_digits=10, decimal_places=2)
tran_amt2 = models.DecimalField(max_digits=10, decimal_places=2, default=0)
cmte_id = models.CharField(max_length=255, blank=True, null=True)
intr_namL = models.CharField(max_length=255, blank=True, null=True)
intr_city = models.CharField(max_length=255, blank=True, null=True)
intr_state = models.CharField(max_length=255, blank=True, null=True)
intr_zip4 = models.CharField(max_length=255, blank=True, null=True)
intr_self = models.CharField(max_length=255, blank=True, null=True)
int_cmteId = models.CharField(max_length=255, blank=True, null=True)
efiling_link = models.URLField(blank=True, null=True)
date_report_added = models.DateTimeField(auto_now_add=True, blank=True, null=True)
date_efiling_added = models.DateTimeField(blank=True, null=True)
county = models.ForeignKey(County, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.filer_namL
def get_datetime_report_date(self):
return datetime.strptime(self.rpt_date, '%Y-%m-%d %H:%M:%S')
class Meta:
unique_together = ('tran_id', 'form_type')
# api/urls
from django.conf.urls import url
from django.urls import path, include
from rest_framework import routers
from .viewsets import registration_views as reg_views
from . import views
router = routers.SimpleRouter()
# Register router with Viewsets from the registration views file
router.register(r'users', reg_views.UserViewSet, basename="users")
router.register(r'reports', views.ReportViewSet, basename="reports") #/api/v1/reports/
report_list = views.ReportViewSet.as_view({
'get': 'list',
'post': 'retrieve'
})
urlpatterns = [
path('store/', views.api_store, name="store"),
path('stop_store/', views.api_store_stop, name="stop_store"),
path('poll_store_status/', views.poll_store_status, name="poll_store_status"),
path('scrape/', views.api_scrape, name="scrape"),
path('stop_scrape/', views.api_scrape_stop, name="stop_scrape"),
path('poll_scrape_status/', views.poll_scrape_status, name='poll_scrape_status'),
path('get_items/', views.get_items, name="get_items"),
path('get_all_items/', views.get_all_items, name="get_all_items"),
path('get_netviz_reports/', views.get_netviz_reports, name='get_netviz_reports'),
path('get_datatables_items/', report_list, name='report_list'),
]
# main.js
Data.columns = [];
$('th').each(function(item,i){
Data.columns.push({'data': $(this).text().trim()})
});
$('#searchtable').DataTable({
'serverSide': true,
'ajax': {
'url': '/api/get_datatables_items/?format=datatables',
'type': 'POST',
'columns': Data.columns,
'beforeSend': function (request) {
request.setRequestHeader("X-CSRFToken", Cookies.get('csrftoken'));
}
}
});
I'm using djangorestframework, djangorestframework-datatables, and jquery.datatables (frontend). Any help is appreciated.
https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py
Override the create method in ReportViewset
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
#self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
self.perform_create(serializer) is what access the database.

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