I have the following Django model:
from mongoengine import *
from datetime import datetime
class Company(Document):
name = StringField(max_length=500)
class Feedback(Document):
text = StringField(max_length=500)
is_approved = BooleanField(default=False)
date = DateTimeField(default=datetime.now())
I want to add a manytomany field of Feedback in Company
Thanks in advance.
This is not a Django model, but a mongoengine Document. It does not have ManyToManyField. Instead you should probably add a ReferenceField inside a ListField to your Company class, like this:
class Company(Document):
name = StringField(max_length=500)
feedbacks = ListField(ReferenceField(Feedback))
class Feedback(Document):
text = StringField(max_length=500)
is_approved = BooleanField(default=False)
date = DateTimeField(default=datetime.now())
Source: http://docs.mongoengine.org/guide/defining-documents.html#one-to-many-with-listfields
Related
I am trying to show a M2M field in a django-table2 as seen in Django-tables2: How to use accessor to bring in foreign columns? and Accessing related models with django-tables2
Using: foreigncolumn = tables.Column(accessor='foreignmodel.foreigncolumnname'), I only see a '--'...
# The models:
class Organism(models.Model):
species_name = models.CharField(max_length=200)
strain_name = models.CharField(max_length=200)
eukaryotic = models.BooleanField(default=True)
lipids = models.ManyToManyField('Lipid',blank=True)
class Lipid(models.Model):
lm_id = models.CharField(max_length=100)
common_name = models.CharField(max_length=100,blank=True)
category = models.CharField(max_length=100,blank=True)
#The tables
class OrganismTable(tables.Table):
name = tables.LinkColumn('catalog:organism-detail', text=lambda record: record.species_name, args=[A('pk')])
lp = tables.Column(accessor='Lipid.common_name')
class Meta:
model = Organism
sequence = ['name','lp']
exclude = ['id','species_name']
Any idea what I'm doing wrong?
This does not work so easily for ManyToManyFields because of the simple way Accessor works. You could display the repr of the related QuerySet via 'lipids.all' but that does not seem sufficient here. You can, however, add a property (or method) to your Organism model and use it in the accessor. This way, you can display any custom information related to the instance:
class Organism(models.Model):
# ...
#property
def lipid_names(self):
return ', '.join(l.common_name for l in self.lipids.all()) # or similar
class OrganismTable(tables.Table):
# ...
lp = tables.Column(accessor='lipid_names')
I would recommend then to add a prefetch_related('lipids') to the Organism QuerySet that you pass to the table for better performance.
I'm stuck with (I think) a dummy error on Django that I can't find where it's the fault.
On "catalog/models.py" I have (it connects to a MySQL database):
from django.db import models
class Application(models.Model):
nameApp = models.CharField(max_length=50)
tarification = models.ForeignKey(Tarification)
Then, I'm using django-tables2 (Doc to fill tables) to make tables on Django, so on my tables.py I have:
import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification
class BillTable(tables.Table):
class Meta:
appName = Application.nameApp
userApp = AppCost.userApp
tarifName = Tarification.nameTarif
tarifCost = Tarification.cost
startTime = AppCost.startTime
finishTime = AppCost.finishTime
totalCost = AppCost.totalCost
# add class="paleblue" to <table> tag
attrs = {'class': 'paleblue'}
And I get an error when I render my website:
type object 'Application' has no attribute 'nameApp'
On the line appName = Application.nameApp from BillTable
But, looking at "Database" window on Pycharm I see the table schema and it's:
catalog_application
id
tarification_id
nameApp
other stuff
And looking with MySQL Workbench the schema looks the same. So, why I'm getting this error?
Regards.
As Daniel Roseman mentioned above, the code you might looking for is below, it does not need a new model:
import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification
class AppCostTable(tables.Table):
userApp = tables.Column()
startTime = tables.Column()
finishTime = tables.Column()
totalCost = tables.Column()
class Meta:
model = AppCost
class ApplicationTable(tables.Table):
appName = tables.Column(accessor='nameApp')
class Meta:
model = Application
class TarificationTable(tables.Table):
tarifName = tables.Column(accessor='nameTarif')
tarifCost = tables.Column(accessor='cost')
class Meta:
model = Tarification
class BillTable(AppCostTable, ApplicationTable, TarificationTable, tables.Table):
pass
If you do not mind to have another model, then inside your catalog.models you can add a new Bill model:
class Bill(models.Model):
application = models.ForeignKey('Application')
appcost = models.ForeignKey('AppCost')
tarification = models.ForeignKey('Tarification')
In your table file:
from catalog.models import Bill
class BillTable(tables.Table):
appName = tables.Column(accessor='application.nameApp')
tarifName = tables.Column(accessor='tarification.nameTarif')
tarifCost = tables.Column(accessor='tarification.cost')
userApp = tables.Column(accessor='appcost.userApp')
startTime = tables.Column(accessor='appcost.startTime')
finishTime = tables.Column(accessor='appcost.finishTime')
totalCost = tables.Column(accessor='appcost.totalCost')
class Meta:
model = Bill
You're very confused about how to use django-tables. You need to specify one model in the Meta class, then just the fields attribute to add a list of fields from that model, as strings, to display. You can't just specify fields from three arbitrary models.
I'm working now on my first Django project. I want to render results table which contains all fields from Priekabos model and one custom column from Grafikas which should contain something similar to:
SELECT max(kada_moketi) FROM grafikas WHERE priekabos_id = ?
Whatever I try from examples nothing works. Should I write another view function with that custom query:
(Grafikas.objects.filter(priekabos_id=1)
neither with:
.aggregate(Max('kada_moketi')
neither with:
.latest('kada_moketi')
worked for me I created a new table class in tables.py which later PriekabosTable will inherit? That didn't work for me too.
Here's my code:
models.py
class Grafikas(models.Model):
id = models.AutoField(primary_key=True)
mokejimo_nr = models.IntegerField()
kada_moketi = models.DateField()
priekabos = models.ForeignKey('Priekabos', models.DO_NOTHING)
class Priekabos(models.Model):
id = models.AutoField(primary_key=True)
sutarties_nr = models.CharField(unique=True, max_length=45, verbose_name='Sut. Nr.')
nuomos_pradz = models.DateField()
sutarties_trukme = models.IntegerField()
views.py
def priekabos_table(request):
table = PriekabosTable(Priekabos.objects.all())
RequestConfig(request, paginate={'per_page': 20}).configure(table)
return render(request, 'isperkamoji_nuoma/priekabos_table.html', {'table': table})
tables.py
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz')
For better understanding, here's 'grafikas' table:
MySQL 'grafikas' table
It sounds like you might be able to fetch the extra field using annotate.
from django.db.models import Max
queryset = Priekabos.objects.annotate(max_kada_moketi=Max('grafikas__kada_moketi'))
table = PriekabosTable(queryset)
Remember to add the field to your table.
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz', 'max_kada_moketi')
I've been looking at the docs for search_fields in django admin in the attempt to allow searching of related fields.
So, here are some of my models.
# models.py
class Team(models.Model):
name = models.CharField(max_length=255)
class AgeGroup(models.Model):
group = models.CharField(max_length=255)
class Runner(models.Model):
"""
Model for the runner holding a course record.
"""
name = models.CharField(max_length=100)
agegroup = models.ForeignKey(AgeGroup)
team = models.ForeignKey(Team, blank=True, null=True)
class Result(models.Model):
"""
Model for the results of records.
"""
runner = models.ForeignKey(Runner)
year = models.IntegerField(_("Year"))
time = models.CharField(_("Time"), max_length=8)
class YearRecord(models.Model):
"""
Model for storing the course records of a year.
"""
result = models.ForeignKey(Result)
year = models.IntegerField()
What I'd like is for the YearRecord admin to be able to search for the team which a runner belongs to. However as soon as I attempt to add the Runner FK relationship to the search fields I get an error on searches; TypeError: Related Field got invalid lookup: icontains
So, here is the admin setup where I'd like to be able to search through the relationships. I'm sure this matches the docs, but am I misunderstanding something here? Can this be resolved & the result__runner be extended to the team field of the Runner model?
# admin.py
class YearRecordAdmin(admin.ModelAdmin):
model = YearRecord
list_display = ('result', 'get_agegroup', 'get_team', 'year')
search_fields = ['result__runner', 'year']
def get_team(self, obj):
return obj.result.runner.team
get_team.short_description = _("Team")
def get_agegroup(self, obj):
return obj.result.runner.agegroup
get_agegroup.short_description = _("Age group")
The documentation reads:
These fields should be some kind of text field, such as CharField or TextField.
so you should use 'result__runner__team__name'.
I'm using Django forms and need to create a list box.
What would be the equivalent of listbox in Django form fields?
I checked the documentation #
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield
but unable to find it.
Here is my code snippet,
Models.py
class Volunteer(models.Model):
NO_OF_HRS = (('1','1')
('2','2'))
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=300)
roledesc = models.CharField(max_length=300)
Duration = models.CharField(choices=NO_OF_HRS,max_length=1)**
forms.py
class VolunteerForm(forms.ModelForm)
datecreated = forms.DateField(label=u'Creation Date')
volposition = forms.CharField(label=u'Position Name', max_length=300)
roledesc = forms.roledesc(label=u'Role description',max_length=5000)
Duration = forms.CharField(widget=forms.select(choices=NO_OF_HRS),max_length=2)
When I try to run, I get the following error,
NO_OF_HRS is not defined
Your NO_OF_HRS tuple is defined inside the model and not available to the form. It has to be imported in forms.py just like any other Python object. Try moving the tuple outside the model definition and import in your forms.py like this:
models.py
NO_OF_HRS = (('1','1')
('2','2'))
class Volunteer(models.Model):
# ...
duration = models.CharField(choices=NO_OF_HRS, max_length=1)
forms.py
from path.to.models import NO_OF_HRS
class VolunteerForm(forms.Form):
# ...
duration = forms.CharField(widget=forms.Select(choices=NO_OF_HRS), max_length=1)
It also looks like you want to use a ModelForm. In this case you don't need to add any field definitions to your VolunteerForm, simply set your model in the inner Meta class.
forms.py
from path.to.models Volunteer
class VolunteerForm(forms.ModelForm):
class Meta:
model = Volunteer