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)
Related
How can make my model so that its ManyToMany Refer to User
class User(AbstractUser):
teacher_or_student = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
grade = models.CharField(max_length=100)
laptop_yes_or = models.CharField(max_length=100)
students = models.ManyToManyField(User)
You can pass the 'self' string for this. By default a ManyToManyField that refers to itself, is als symmetrical, so you probably want to turn that off, since if a is a student of b, then b is not per se a student of a. You can do that by specifying symmetrical=False [Django-doc]:
class User(AbstractUser):
teacher_or_student = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
grade = models.CharField(max_length=100)
laptop_yes_or = models.CharField(max_length=100)
students = models.ManyToManyField(
'self',
symmetrical=False,
related_name='teachers'
)
I have two models (Product & Category) which every product has a linked category.
I have installed DjangoFilterBackend which the hope of filtering on the category field to return a list of products in that category.
However, whenever I send the query in Postman. I receive the error Select a valid choice. That choice is not one of the available choices..
I have tried filtering on another field in my product model (name for an example) and that works fine. So i'm not sure if i'm missing something for category to work.
Product/View.py:
class ProductView(ListAPIView):
serializer_class = ProductSerializer
queryset = Product.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_fields = ('category', 'name')
Products/Models.py:
class Product(models.Model):
name = models.CharField(max_length=250, unique=True, blank=False)
photo = models.ImageField(upload_to=product_photo_path)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.IntegerField()
description = models.TextField(blank=False)
price = models.DecimalField(max_digits=6, decimal_places=2)
in_stock = models.BooleanField(default=False)
trending = models.BooleanField(default=False)
def __str__(self):
return self.name
Products/serializers.py
class ProductSerializer(serializers.ModelSerializer):
category = serializers.CharField(source='category.name', read_only=True)
class Meta:
model = Product
fields = ('category', 'name', 'photo', 'quantity', 'description', 'price', 'in_stock', 'trending')
The query I am using is a GET request to:
http://127.0.0.1:8000/api/products?category=xxxx - I am sending no payload. The response I am receiving is a `400 Bad Request` and the exact error is:
{
"category": [
"Select a valid choice. That choice is not one of the available choices."
]
}
Ah-ha!
I changed the model to:
class Product(models.Model):
name = models.CharField(max_length=250, unique=True, blank=False)
photo = models.ImageField(upload_to=product_photo_path)
**category = models.ForeignKey(Category, to_field='name', on_delete=models.CASCADE)**
quantity = models.IntegerField()
description = models.TextField(blank=False)
price = models.DecimalField(max_digits=6, decimal_places=2)
in_stock = models.BooleanField(default=False)
trending = models.BooleanField(default=False)
And now it works!
Well, I am not sure, but try to filter on field category_id, this field is created automatically for FK fields
Just in case somebody will ever need the answer, to be able to use the name of a foreign field to filter instead of the primary key use a double underscore i.e category__name in this case. Note that name in this case is the field of the foreign model that you want to filter with and you can replace it with your field accordingly.
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!
In Django there are field types called ForeignKey and OneToMany/OneToOne, I was wondering would I use ForeignKey or the relationship type as the field type in this scenario? User to Profile has been identified as OneToOne but I'm unsure about the others.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
fullname = models.CharField(max_length=100)
dob = models.DateField()
address = models.TextField()
city = models.CharField(max_length=100)
profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images')
class Product(models.Model):
name = models.CharField(max_length=100)
brand = models.CharField(max_length=100)
cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
category = models.CharField(max_length=100)
releasedate = models.DateField()
description = models.TextField()
productphoto = models.ImageField(default='default_product.jpg', upload_to='reviewApp/static/product_images')
class Review(models.Model):
product = models.ForeignKey(Product)
profile = models.ForeignKey(Profile)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rating = model.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)])
reviewtext = models.TextField()
postdate = models.DateTimeField(auto_now_add=True)
lastmodified = models.DateTimeField(auto_now=True)
So from what I see here, it seems to be good if the following is what you want:
User can have only one profile and one Profile is related to only one user.
a Profile can make multiple Review but a Review belongs to only one profile.
A Product can have multiple Review but a Review is specific to one Product.
Be carefull to define the on_delete argument for your foreign keys depending of what you want to keep in your database after a delete.
More info from the doc : https://docs.djangoproject.com/fr/2.2/ref/models/fields/#arguments
I've tried reading the docs and previous answers to this question without much luck.
I've got a bunch of student-course registrations and I'd like to see some of those selected registrations in conjunction with some of the attributes of the students. No luck so far...I'd request your advice!
Here's the model:
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
netID = models.CharField(max_length=8)
class Registration(models.Model):
student = models.ForeignKey(Student)
course = models.ForeignKey(Course)
attendance_M = models.BooleanField(default=False)
attendance_Tu = models.BooleanField(default=False)
and here is the tables.py:
class AttendanceTable(tables.Table):
netID = tables.Column(accessor='Student.netID')
first = tables.Column(accessor='Student.first_name')
last = tables.Column(accessor='Student.last_name')
class Meta:
model = Registration
attrs = {"class": "paleblue"}
fields = ('attendance_M', 'attendance_Tu',)
sequence = ('netID', 'first', 'last', 'attendance_M', 'attendance_Tu',)
While I'm getting data on the attendance values, there's nothing from the student foreign columns.
netID First Last Attendance M Attendance Tu
— — — ✔ ✘
And it's the same deal if I start the Table with model = Student and use accessors against the Registration table, it's the same deal.
I feel like I'm missing something very conceptual and crucial -- please guide me!
The model name in the accessor parameter of the column should be lowercase.
Use accessor='student.netID' instead of accessor='Student.netID'.
When using the accessor parameter, you have to use the field name stated in the Model that has the foreign key, and then select which field from that table you want to use.
So, for these models:
#models.py
class Description_M(models.Model):
id_hash = models.CharField(db_column='Id_hash', primary_key=True, max_length=22)
description = models.CharField(db_column='Description', max_length=255, blank=True, null=True)
class GeoCodes(models.Model):
geo = models.CharField(db_column='Geo', primary_key=True, max_length=5)
city_name = models.CharField(db_column='City', max_length=150, blank=True, null=True)
class RefSources(models.Model):
id_source = models.IntegerField(db_column='Id_source', primary_key=True,)
source_name = models.CharField(db_column='Source', max_length=150, blank=True, null=True)
class Price(models.Model):
id_hash = models.ForeignKey(Description_M, models.DO_NOTHING, db_column='Id_hash')
date= models.ForeignKey(DateTime, models.DO_NOTHING, db_column='Date')
geo = models.ForeignKey(GeoCodes, models.DO_NOTHING, db_column='Geo')
id_source = models.ForeignKey(RefSources, models.DO_NOTHING, db_column='Id_source') # Field name made lowercase.
price = models.FloatField(db_column='Price',primary_key=True, unique=False,default=None)
When using the foreign key to pull fields from that table, you have to:
class price_table(tables.Table):
description = tables.Column(accessor = 'id_hash.description')
city = tables.Column(accessor = 'geo.city_name')
source = tables.Column(accessor = 'id_source.source_name')
class Meta:
model = Price
fields = ['date','price']
sequence = ['description ','date','city ','source','price']
template_name = 'django_tables2/bootstrap.html'