I'm using django-tables-2 for a project. I have a table that uses a model for displaying data but I need to add one more column to display some informations from another table. Can I do that?
Have you tried the following?
# models.py
class Person(models.Model):
" This is your regular model "
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
user = models.ForeignKey("auth.User")
dob = models.DateField()
class PersonTable(tables.Table):
id = tables.Column(name="id") # just add a field here
class Meta:
model = Person
You map the column either by having the same name of the model's attribute, either using the accessor property.
I guess in your case it would be:
class UsersTable(tables.Table):
custom = Column(_("Custom"), accessor='id', orderable=False) # Any attr will do, dont mind it
def render_custom(self, record):
return services.get_some_info(record)
class Meta:
model = User
fields = (b'username', )
Related
My model looks like this.
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
roll_no = models.CharField(max_length=32)
course = models.CharField(max_length=120)
Now I want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field doesn't have any unique id.
I tried this:
class StudentFilter(django_filters.FilterSet):
course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course'))
class Meta:
model = Student
fields = []
but it didn't work.
Note I do not want to make separate model for course.
The AllValuesFilter does exactly what you are asking for I believe
class StudentFilter(django_filters.FilterSet):
course = django_filters.AllValuesFilter(field_name="course")
class Meta:
model = Student
fields = []
The requirement is "I want to insert person with the person groups selection and also at the time of Creating person group I can choose persons for that particular group".
I've added two models in my models.py and manage many to many relationship between.
models.py
from django.db import models
class PersonGroup(models.Model):
id = models.AutoField(primary_key=True)
groupName = models.CharField(max_length=30)
detail = models.CharField(max_length=200)
class Person(models.Model):
id = models.AutoField(primary_key=True)
personId = models.CharField(max_length=20)
personName = models.CharField(max_length=20)
state = models.IntegerField()
personGroup = models.ManyToManyField(PersonGroup, related_name="person_list", blank=True)
serializers.py
class PersonSerializer(serializers.ModelSerializer):
personGroup = serializers.PrimaryKeyRelatedField(queryset=PersonGroup.objects.all(), many=True)
class Meta:
model = Person
fields = '__all__'
class PersonGroupSerializer(serializers.ModelSerializer):
person_list = PersonSerializer(many=True, read_only=True)
class Meta:
model = PersonGroup
fields = '__all__'
The above code help me to create person with personGroup selection
But, I also want to add persons selection at the time of create personGroup. Currently at the time of creating personGroup I'm not allowed to enter persons.
Please let me know if there any solution by which I can also select available persons at the time of person group creation.
Your person_list field in the PersonGroupSerializer is on read only, so you can't modify it using the API.
person_list = serializers.PrimaryKeyRelatedField(queryset=Person.objects.all(), many=True)
Try removing this arg.
You might also want to switch to a ForeignKey field instead of slugged.
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company_name = models.CharField(max_length=254)
Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:
class Company(BaseModel):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
What should be my Field Choice in the UserProfile model for user_company_name field.
Why don't just add ForeignKey to UserProfile model? Example below.
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)
You need ForeignKey for this field
user_company_name
https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey
read this doc
You can use foreign key in the models for user_company and in forms use ChoiceField to get a drop down.
Check the code below:-
In models:-
class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)
In Forms:-
user_company = forms.ModelChoiceField(queryset=Company.objects.all())
I know that django will helpfully generate a through table for simple many-to-many tables. However if you want to add information about the relationship, you need a 'linker' or through table. This example from the docs gives an example:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
I have in my design several tables/models like group, that vary mostly just by their choices attribute. And I'll be adding more later.
Is it possible to customize what sort of through table is generated by Django's magic? If so is this sensible?
The sort of thing I'm talking about is this:
class CharacterSkillLink(models.Model):
character = models.ForeignKey('NWODCharacter', related_name='%(class)s_by_skill')
skill = models.ForeignKey('Skill', choices = SKILL_CHOICES)
value = models.IntegerRangeField(min_value=1, max_value=5)
speciality = models.CharField(max_length=200)
class CharacterAttributeLink(models.Model):
character = models.ForeignKey('NWODCharacter', related_name='%(class)s_by_skill')
attribute = models.ForeignKey('Attribute', choices = ATTRIBUTE_CHOICES)
value = model.IntegerRangeField(min_value=1, max_value=5
class CharacterArcanaLink(models.Model):
character = models.ForeignKey('Mage', related_name='%(class)s_by_skill')
arcana = models.ForeignKey('Arcana', choices = ARCANA_CHOICES)
value = model.IntegerRangeField(min_value=1, max_value=5
In the future there'll be more like these. It's be handy if there was some way to django, much like with the through_field attribute, which defines keys on the through table to use, that there should be extra values to add to it (e.g. extra_field=value).
Is this possible/sensible?
IMO, adding fields to a "through" table is a great pattern for many possible uses. I'm not sure that Django needs new syntax to handle this case, but if you think you're creating lots of these tables and mixing/matching different tables, perhaps some abstract mixins will simplify things. For Example:
class CharacterLink(models.Model):
character = models.ForeignKey('NWODCharacter')
class Meta:
abstract = True
class SkillLink(models.Model):
skill = models.ForeignKey('Skill', choices = SKILL_CHOICES)
class Meta:
abstract = True
class AttributeLink(models.Model):
attribute = models.ForeignKey('Attribute', choices = ATTRIBUTE_CHOICES)
class Meta:
abstract = True
class CharacterSkillLink(CharacterLink, SkillLink):
value = models.IntegerRangeField(min_value=1, max_value=5)
speciality = models.CharField(max_length=200)
class CharacterAttributeLink(CharacterLink, AttributeLink):
value = model.IntegerRangeField(min_value=1, max_value=5)
I have django model
class TestResult(models.Model):
chemical_name = char(50)
value =char(50)
unit = choices(UNIT_CHOICES)
method = choices(METHOD_CHOICES)
CSUSNormal = char(50)
CSUSCaution = char(50)
In admin page this model consist of 180 records. Now i want to apply ordering for these records by creating field order_num. how can i set the ordering based on the order_num of each field?
I admin page i want to see all the records based on the order_num field. How can i achieve this?
Meta.ordering
class TestResult(models.Model):
chemical_name = models.CharField(max_length=50)
value =models.CharField(max_length=50)
unit = models.CharField(choices=UNIT_CHOICES)
method = models.CharField(METHOD_CHOICES)
CSUSNormal = models.CharField(max_length=50)
CSUSCaution = models.CharField(max_length=50)
order_num=models.IntegerField()
class Meta:
ordering=" order_num"