Foreignkeyfield - verbose name not shown in form - python

my verbose_name of a foreignkeyfield isn't printed in my forms. (I create the modelforms via modelformset_factory
model
class MOrders(models.Model):
amount = models.IntegerField('Bestellmenge', null=True, blank=True)
order_date = models.DateField('Bestelldatum')
id = models.AutoField(primary_key=True)
m_product_types = models.ForeignKey(MProductTypes)
class Meta:
db_table = u'm_orders'
verbose_name = 'Bestellung'
verbose_name_plural = 'Bestellungen'
unique_together = (('id','order_date','m_product_types'))
def __unicode__(self):
return "%s" % (self.order_date)
verbose_name of m_product_types is set. B
class MProductTypes(models.Model):
id = models.AutoField(primary_key=True)
stock = models.IntegerField('Bestand',null=True, blank=True)
m_products = models.ForeignKey(MProducts, verbose_name='Produkt')
m_sizes = models.ForeignKey(MSizes, verbose_name='Groesse')
m_colors = models.ForeignKey(MColors, verbose_name='Farbe')
class Meta:
verbose_name = u'Produktart'
verbose_name_plural = 'Produktarten'
db_table = u'm_product_types'
Am I doing something wrong? I'm using the latest Django version from trunk.

m_product_types = models.ForeignKey(MProductTypes,
verbose_name = u'Produktart',
)

Related

Django model organization issue

I'm developing recipe and ingredient models.
models.py:
class Recipe(models.Model):
"""Recipe structure"""
author = models.ForeignKey(
User, on_delete=models.CASCADE
)
title = models.CharField(max_length=40, unique=True)
picture = models.ImageField(blank=True, null=True)
text = models.TextField(max_length=100, blank=True, null=True)
components = models.ManyToManyField('Component')
tag = MultiSelectField(max_length=10, choices=tags)
cooking_time = models.IntegerField(
validators=[MinValueValidator(1, 'Value cannot be lower than 1')]
)
slug = models.SlugField()
def __str__(self):
return self.title
class Meta:
db_table = 'recipes'
verbose_name = 'Рецепт'
verbose_name_plural = 'Рецепты'
class Component(models.Model):
"""Component structure"""
title = models.CharField(max_length=50, unique=True)
unit = models.CharField(max_length=10, choices=units)
def __str__(self):
return self.title
class Meta:
db_table = 'components'
verbose_name = 'Ингредиент'
verbose_name_plural = 'Ингредиенты'
class Component_quantity(models.Model):
"""Table linking quantity with recipe and component together"""
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
component = models.ForeignKey(Component, on_delete=models.CASCADE)
quantity = models.DecimalField(
max_digits=5,
decimal_places=1,
verbose_name='Количество',
validators=[MinValueValidator(1)]
)
class Meta:
db_table = 'quantity_and_recipe_linking_table'
unique_together = ('recipe', 'component')
verbose_name = 'Ингредиент в рецепте'
verbose_name_plural = 'Ингредиенты в рецепте'
The problem is to link the recipe and the component in the Component_quantity model so that in the component field it is possible to select only those entities that are specified in the recipe itself. Is it possible to do this?
I would recommend to put the quantity field directly into the Component model. Another way to do it is to add a quantity foreignkey to the Component model and then remove the recipe and component foreignkey from the Component_quantity model.

Django model that stores multiple other models that store multiple other models

I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this.
Test
-Event1
--Property1
--Property2
--Property3
--Property4
-Event2
--Property1a
--Property2b
--Property3c
--Property4d
-Event3
--Property1aa
--Property2bb
--Property3cc
--Property4dd
-Event4
--Property1aaa
--Property2bbb
--Property3ccc
--Property4ddd
I want to have multiple tests. My current model setup looks like this:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test_id = models.IntegerField()
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want to be able to pick the properties and add them to my event. Then I want to be able to go to the Test page and add the events to it.
A good example of what I am trying to create is a replica of this: http://jsonparser.tools/tests.php
you should define foreign keys for events and properties:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test = models.ForeignKey(Test,on_delete=models.CASCADE)
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
event = models.ForeignKey(Event,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
this should solve your problem if not let me know happy to help.

How to save three related models in one DRF endpoint?

I have 4 related models and I need to implement the functionality to consistently create instances of these models in a database in one post query. For this I use override of the APIView class post method.
models
class VendorContacts(models.Model):
contact_id = models.AutoField(primary_key=True)
vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE)
contact_name = models.CharField(max_length=45, blank=True)
phone = models.CharField(max_length=45, blank=True)
email = models.CharField(max_length=80, blank=True, unique=True)
class Meta:
db_table = 'vendor_contacts'
class VendorModuleNames(models.Model):
vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True)
module = models.ForeignKey(Modules, models.DO_NOTHING)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'vendor_module_names'
unique_together = (('vendor', 'module'),)
class Vendors(models.Model):
COUNTRY_CHOICES = tuple(COUNTRIES)
vendorid = models.AutoField(primary_key=True)
vendor_name = models.CharField(max_length=45, unique=True)
country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
nda = models.DateField(blank=True, null=True)
user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'vendors'
unique_together = (('vendorid', 'timestamp'),)
class Modules(models.Model):
MODULES_NAME =tuple(MODULES)
mid = models.AutoField(primary_key=True)
module_name = models.CharField(max_length=50, choices=MODULES_NAME)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'modules'
unique_together = (('mid', 'timestamp'),)
serializer.py
class VendorsSerializer(serializers.ModelSerializer):
class Meta:
model = Vendors
fields = ('vendor_name',
'country',
'nda',)
class VendorContactSerializer(serializers.ModelSerializer):
class Meta:
model = VendorContacts
fields = (
'contact_name',
'phone',
'email',)
class VendorModulSerializer(serializers.ModelSerializer):
class Meta:
model = VendorModuleNames
fields = ('module',)
class ModulesSerializer(serializers.ModelSerializer):
class Meta:
model = Modules
fields = ('module_name', )
views.py
class VendorsCreateView(APIView):
"""Create new vendor instances from form"""
def post(self, request, *args, **kwargs):
vendor_serializer = VendorsSerializer(data=request.data)
vendor_contact_serializer = VendorContactSerializer(data=request.data)
vendor_modules_serializer = VendorModulSerializer(data=request.data)
module_serializer = ModulesSerializer(data=request.data)
try:
vendor_serializer.is_valid(raise_exception=True) \
and vendor_contact_serializer.is_valid(raise_exception=True) \
and vendor_modules_serializer.is_valid(raise_exception=True) \
and module_serializer.is_valid(raise_exception=True)
vendor_serializer.save(user_id=request.user)
# ....
# Some new logic here ????
# ...
except ValidationError:
return Response({"errors": (vendor_serializer.errors,
vendor_contact_serializer.errors,
vendor_modules_serializer.errors
)},
status=status.HTTP_400_BAD_REQUEST)
else:
return Response(request.data, status=status.HTTP_200_OK)
There is no problem saving one Vendor model, but I can't imagine how to save cascading all related models in a single request.
save returns the newly saved object, which you can then pass into the subsequent save() methods:
vendor = vendor_serializer.save(user_id=request.user)
module = module_serializer.save()
vendor_module = vendor_modules_serializer.save(module=module, vendor=vendor)
vendor_contact = vendor_contact_serializer.save(vendor=vendor)

How to get data from two models in Django

I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table.
I have two tables job_info and username_userid.
Here is my models.class file:
class UseridUsername(models.Model):
userid = models.IntegerField(blank=True, null=True)
username = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'userid_username'
class LinuxJobTable(models.Model):
job_db_inx = models.AutoField(primary_key=True)
mod_time = models.IntegerField()
account = models.TextField(blank=True, null=True)
exit_code = models.IntegerField()
job_name = models.TextField()
id_job = models.IntegerField()
id_user = models.IntegerField()
class Meta:
managed = False
db_table = 'linux_job_table'
Heren is my serializable class :
class UseridUsernameSerializer(serializers.ModelSerializer):
class Meta:
model = UseridUsername
fields = ('userid','username')
class UserSerializer(serializers.ModelSerializer):
class Meta:
username = UseridUsernameSerializer(many=False)
model = LinuxJobTable
fields = ('account','mod_time','username')

Django-rest-framework drf-extensions: Nested routers/urls are not filtering

I can't get the my Router to filter my requests based on the "parents_query_lookup".
Here's my code:
urls.py:
from rest_framework_extensions.routers import ExtendedSimpleRouter
from .views import OrganizationViewSet, GroupViewSet, BootGroupViewSet
router = ExtendedSimpleRouter()
(router.register(r'organizations', OrganizationViewSet,
base_name='organization')
.register(r'groups', GroupViewSet, base_name='organizations-group',
parents_query_lookups=['resource__organization'])
.register(r'boot_groups', BootGroupViewSet,
base_name='organizations-groups-boot_group',
parents_query_lookups=['group__resource__organization', 'group']))
urlpatterns = router.urls
views.py:
from rest_framework.viewsets import ModelViewSet
from rest_framework_extensions.mixins import NestedViewSetMixin
from .models import Organization, OrganizationSerializer, \
Group, GroupSerializer, BootGroup, BootGroupSerializer
class OrganizationViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Organization.objects.all()
serializer_class = OrganizationSerializer
class GroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
class BootGroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = BootGroup.objects.all()
serializer_class = BootGroupSerializer
enums.py:
class ResourceTypeEnum:
RESOURCE_TYPE_GROUP = 'group'
RESOURCE_TYPE_VM = 'vm'
RESOURCE_TYPE_CHOICES = (
(RESOURCE_TYPE_GROUP, RESOURCE_TYPE_GROUP),
(RESOURCE_TYPE_VM, RESOURCE_TYPE_VM)
)
models.py:
from django.db.models import Model
from rest_framework.serializers import ModelSerializer
from .enums import ResourceTypeEnum
class Organization(Model):
organization_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', blank=True, null=True)
class Meta:
unique_together = (("name", "parent"))
verbose_name = "Organization"
verbose_name_plural = "Organizations"
app_label = 'api_manager'
db_table = 'organization'
def __unicode__(self):
return self.name
class OrganizationSerializer(ModelSerializer):
class Meta:
model = Organization
fields = ('name', 'parent')
depth = 2
class Resource(Model):
resource_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=55)
type = models.CharField(
max_length=5, choices=ResourceTypeEnum.RESOURCE_TYPE_CHOICES)
organization = models.ForeignKey(Organization)
class Meta:
verbose_name = "Resource"
verbose_name_plural = "Resources"
app_label = 'api_manager'
db_table = 'resource'
def __unicode__(self):
return self.name
class ResourceSerializer(ModelSerializer):
class Meta:
model = Resource
fields = ('name', 'type', 'organization')
depth = 2
class Group(Model):
resource = models.OneToOneField(Resource, primary_key=True)
is_consistent = models.BooleanField()
parent = models.ForeignKey('self', blank=True, null=True)
class Meta:
verbose_name = "Group"
verbose_name_plural = "Groups"
app_label = 'api_manager'
db_table = 'group'
def __unicode__(self):
return "%s: %s" % (self.resource.organization, self.resource)
class GroupSerializer(ModelSerializer):
class Meta:
model = Group
fields = ('resource', 'is_consistent', 'parent')
depth = 2
class BootGroup(Model):
boot_group_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
boot_order = models.PositiveSmallIntegerField(default=1)
group = models.ForeignKey(Group)
class Meta:
unique_together = (("boot_order", "group"))
verbose_name = "BootGroup"
verbose_name_plural = "BootGroups"
app_label = 'api_manager'
db_table = 'boot_group'
def __unicode__(self):
return "%s: %s" % (self.group.resource, self.name)
class BootGroupSerializer(ModelSerializer):
class Meta:
model = BootGroup
fields = ('name', 'boot_order', 'group')
depth = 2
class Vm(Model):
resource = models.OneToOneField(Resource, primary_key=True)
hostname = models.CharField(max_length=200, blank=True, null=True)
group = models.ForeignKey(Group, blank=True, null=True)
boot_group = models.ForeignKey(BootGroup, blank=True, null=True)
class Meta:
verbose_name = "Vm"
verbose_name_plural = "Vms"
app_label = 'api_manager'
db_table = 'vm'
def __unicode__(self):
return "%s: %s" % (self.resource.organization, self.resource)
class VmSerializer(ModelSerializer):
class Meta:
model = Vm
fields = ('resource', 'hostname', 'group', 'boot_group')
depth = 2
No matter what I try, something like "organizations/1/groups" returns all of the Group models, regardless of Organization. Am I missing something? Thanks in advance for the help.
Based on yours router definition, you need to define a queryset in GroupViewSet
from rest_framework_extensions.utils import compose_parent_pk_kwarg_name
def get_queryset(self):
resource_id = self.kwargs.get(compose_parent_pk_kwarg_name('resource_organization')
return Group.objects.filter(resource=resource_id)
The filter value can be find in kwargs as parent_lookup_<parents_query_lookups> or you can retrieve the parent query dict with self.get_parents_query_dict()

Categories

Resources