I'm trying to get a PurchaseOrder that can be added indefinitely many times. Maybe this is easier than I am thinking, but here is my problem in this imagine:
I would like it to where instead of adding another VendorProfile, it'll add another PurchaseOrder. My end goal is to be able to add 1, 2, 20, etc. PurchaseOrder from the same add screen. Not to be able to add a PurchaseOrder, and then a VendorProfile.
Here's some code: In models.py
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
vendor = models.ForeignKey('VendorProfile')
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
In admin.py
class ProductInline(admin.StackedInline):
model = VendorProfile
extra = 3
class PurchaseOrderAdmin(admin.ModelAdmin):
#...
inlines = [ProductInline]
If I understand you correctly, you whant associate many PurchaseOrder's to one VerndorProfile. In such a case it would be better to use ManyToManyField.
Example:
models.py:
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
def __unicode__(self):
return u'{} {}'.format(self.product, self.dollar_amount)
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
purchased_orders = models.ManyToManyField('PurchaseOrder')
admin.py
class VendorProfileAdmin(admin.ModelAdmin):
filter_horizontal = ('purchased_orders', )
admin.site.register(VendorProfile, VendorProfileAdmin)
Related
I am Developing a E-commerce Application with Django
So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.
So Here is the code for this
This is the model for getting the Categories from the user
class ProjektCat(models.Model):
id = models.AutoField(primary_key=True)
Option_Name = models.CharField(max_length=50)
Option_Number = models.IntegerField()
Number_Visits = models.IntegerField(default=0)
def __str__(self):
return f'{self.Option_Name}'
and here is the code to list those categories as a dropdown in the CharField
class Software_And_Service(models.Model):
id = models.AutoField(primary_key=True)
Product_Name = models.CharField(max_length=100, default='')
projectKats = ProjektCat.objects.all()
choice = []
for i in projectKats:
option = (i.Option_Number, i.Option_Name)
choice.append(option)
Cateogary = models.CharField(
max_length=256, choices=choice)
Price = models.IntegerField(default=0)
Description = models.TextField(default='', max_length=5000)
pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
image = models.URLField(default='')
linkToDownload = models.URLField(default='')
def __str__(self):
return f'Projekt : {self.Product_Name}'
But it's Showing me an Error that there is no such table in app_name.projektcat
Is there is any solution for this??
It's not how you do this. First correctly assign the projectKats field i.e
# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)
You need to do this logic in django forms rather than django models.
So this is how you can do it.
forms.py
from django import forms
from .models import ProjektCat, Software_And_Service
def get_category_choices():
return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]
class SoftwareAndServiceForm(forms.ModelForm):
projectKats = forms.ChoiceField(choices=get_category_choices)
class Meta:
model = Software_And_Service
fields = [
'projectKats',
# whatever fields you want
]
This question is similar with others but it is a different one actually ! So, I have 3 models such as (I have deleted some unnecessary things for shorter code):
class Category(models.Model):
category_title = models.CharField(max_length=200)
category_content = models.TextField()
category_slug = models.CharField(max_length=200)
def __str__(self):
return self.category_title
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.classes_title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.subject_title
So let me give an example. I can have 2 categories and in those categories I can have "same named" classes. Lets think about maths is a class for both categories. When I want to add a new subject to maths I see 2 same named maths in admin page. So I want to know which one belongs to which category in admin page. So I can add my subject to right class.
class SubjectAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class',)
So in this picture (Subjects = Konular) I am adding a new subject. I will have a foreign key to Class. However I have same name for classes that are coming from different categories. So in this dropdown how can I know which class belongs to which category ?
Try this...
class KonularAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class', 'get_classes_category_title')
def get_classes_category_title(self, obj):
subject_object = Subjects.objects.get(id=obj.subject_class)
return str(subject_object.classes_category.category_title)
It returns the category title name
If I understood you correctly, This should work.
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {str(self.subject_class)}"
You can use __str__() method to change the string representation of an object:
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {self.subject_content} - {self.subject_class}"
# shorter version:
# return f"{self.subject_title[:10]} - {self.subject_content[:10]} - {self.subject_class[:10]}"
Check it with:
>>> print(Subjects.objects.first())
models.py
class Add_category(models.Model):
Category = models.CharField(max_length=100)
Image = models.ImageField()
MetaKeyword = models.CharField(max_length=100)
MetaDesc = models.CharField(max_length=100)
def __str__(self):
return self.Category
In this, I have tried to add city field and choices must come in this
field by the help of Add_category model but it fails.
class Make_Invoice(models.Model):
Order_no = models.IntegerField()
Invoice_no = models.IntegerField()
Product_name = models.CharField(max_length=100)
Product_Id = models.IntegerField()
Quantity = models.IntegerField()
City = models.CharField(max_length=100, choices = Add_category.Category, default='Select')
Why even use City as a as a CharField? As far as I see it should be a ForeignKey - ManyToOne or even ManyToMany relation.
Check it in the documentation:
https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/
https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/
Use a ForeignKey
City = models.ForeignKey('Add_category', on_delete=models.PROTECT)
the code did not return all of the item's name based on employee..? how to solve this probem? did the models wrong? or the query?
MODELS.PY
class Employee(models.Model):
name = models.CharField(max_length=100)
telephone_number = models.CharField(max_length=20)
address = models.TextField()
email = models.EmailField()
class Item(models.Model):
code = models.CharField(max_length=4)
name = models.CharField(max_length=100)
kind = models.CharField(max_length=100)
description = models.TextField()
class Inventory(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('inventaris-detail', kwargs={'pk': self.pk})
VIEWS.PY
how can i get all of the employee's item ?
query_set = Inventory.objects.all()
for query in query_set:
output.append([
query.employee.name,
query.item.name
])
i need something like query.employee.items_set.all() .. ?
You want to get all of the items from an employee? The following should achieve that:
employee = Employee.objects.all()[0] # Just get a random employee, you can do this with more employees too if you want
employees_items = [inventory.item for inventory in employee.inventory_set.all()]
Your code does not logically make a lot of sense though, to be honest. Most likely, there should be a field on a Item class which is a FK to Inventory. Your item class should probably be:
class Item(models.Model):
code = models.CharField(max_length=4)
name = models.CharField(max_length=100)
kind = models.CharField(max_length=100)
description = models.TextField()
inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE)
(Of course this will not work since Inventory is defined after this class, but you can just put Inventory above it or use one of the other many methods to solve this problem)
Good luck!
Greetings, I have these 2 models:
from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
person = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
fax = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ForeignKey(Office)
def __unicode__(self):
return self.name
I want to be able to select several Offices for Provinces, which is a one to many model. Here is my admin.py:
from harita.haritaapp.models import Province, Office
from django.contrib import admin
class ProvinceCreator(admin.ModelAdmin):
list_display = ['name', 'numberPlate','content','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name','person','phone','fax','address']
admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)
Right now, I am able to select one Office per Province at the admin panel while creating a new Province but I want to be able to select more than one. How can I achieve this?
Regards
I'm not sure if I'm misunderstanding you, but your models currently say "an office can be associated with many provinces, but each province may only have one office". This contradicts what you want. Use a ManyToMany field instead:
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ManyToManyField(Office)
def __unicode__(self):
return self.name