Django DRF Model doesn't show foreign keys in admin panel - python

I have a model in my Django application for review. This model has two foreign keys to the product and user models. But when I go to the admin panel and try to add a new review I don't see the review models dropdown select for the foreign keys.
I'm expecting to see the foreign keys fields rendered in my admin panel as dropdown selects like in the blue box in the picture below.
Screenshot of my admin panel to add a new order object
But the admin panel doesn't show those fields. It only shows the name, rating, and comment fields.
Screenshot of my admin panel to add a new reivew object
Here is my review model.
class Reviews(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True),
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True),
name = models.CharField(max_length=350, null=True, blank=True)
rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0)
comment = models.TextField(null=True, blank=True)
createdAt = models.DateTimeField
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return str(self.rating)

In your Reviews model, you have put a comma at the end of users and product fields. Remove the trailing comma at the end, as the fields are considered as tuple when a comma is present.
It should be:
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
Also, your createdAt field is not correct.
It should be:
createdAt = models.DateTimeField()

Try it like this, i removed comma from user and product field in the end, also i have added () in DateTimeField
class Reviews(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=350, null=True, blank=True)
rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0)
comment = models.TextField(null=True, blank=True)
createdAt = models.DateTimeField()

Related

Delete django models object with duplicate field

I want delete django models object with duplicate field.
for example:
ProgrammingQuestionAnswer.objects.filter(accept=True, programming_question=programming_question)
here, maybe a user has 2 accept in the question. I want to count those duplicates once
this is my model:
class ProgrammingQuestionAnswer(models.Model):
languages = (
('python', 'Python'),
('cpp', 'C++'),
)
programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True)
language = models.CharField(max_length=100, choices=languages, default="python")
time = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True)
accept = models.BooleanField(default=False)

Filter a user data using contains in Django

I have this model that records data in slug. The user has a relation with the award model. What am trying to do is list all login user's awards slug field data in the contain filter so i can use it to filter user's data.
NOTE : All the data in save in the SuccessfulTransactionHistory model field award is in slug format and SuccessfulTransactionHistory model has no foreign key relation to award and user
models.py
class Award(models.Model):
admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='award_images')
slug = models.SlugField(max_length=150, blank=True, null=True)
about_the_award = models.TextField(blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed')
price = models.DecimalField(max_digits=3, default='0.5', decimal_places=1, blank=True, null=True, validators = [MinValueValidator(0.1)])
bulk_voting = models.CharField(max_length=20, choices=BULK_VOTING, default='Closed')
amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2, blank=True,)
results_status = models.CharField(max_length=20, choices=RESULTS_PUBLISHED, default='private')
starting_date = models.DateTimeField()
ending_date = models.DateTimeField()
date = models.DateTimeField(auto_now_add=True)
class SuccessfulTransactionHistory(models.Model):
nominee_name = models.CharField(max_length=120)
transaction_id = models.CharField(max_length=120)
award = models.CharField(max_length=120)
amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2)
status = models.CharField(max_length=120, null=True, blank=True)
phone = models.CharField(max_length=120, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
In my view.py
success_list = SuccessfulTransactionHistory.objects.filter(award__contains=request.user.award.slug).order_by('-date')
This is my error
'User' object has no attribute 'award'
``
Your User object has a lot of awards, because you use ForeignKey.
The relation is: One award has one User, but One user has one or more than one awards (award_set is the property name).
Solutions? Yes, of course,but depends on the context.
1- If the user has only one award, you can use OneToOneField, and your logic is ok.
2- If the user can have more than one Award, may be you need 2 steps.
Step 1: get all award slugs:
award_slugs = list(request.user.award_set.values_list('slug', flat=True))
where award_slugs is a list of slugs.
Step 2: Get success_list:
success_list = SuccessfulTransactionHistory.objects.filter(award__in=award_slugs)

django ForeignKey field should only select by category

I have a ForeignKey field in my model and in Django admin and Django forms` when I display that field or in Django admin, I get all the field that in that model However, I only want to display selected fields in that dropdown, for example
class Area(models.Model):
area_type_options = (('cc', 'Cost Center'), ('pc', 'Profit Center'),)
name = models.CharField(max_length=100)
area_type = models.CharField(max_length=100, choices=area_type_options)
class Item(models.Model):
name = models.CharField(max_length=150, null=True, unique=True)
profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center')
cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center')
I get to see all the records in the cost_center and all the records in the profit_center however I only want to see where area_type is cc to cost_center and where area type pc to profit_center
Please Help
You can use ForeignKey.limit_choices_to [Django docs] to do this:
class Item(models.Model):
name = models.CharField(max_length=150, null=True, unique=True)
profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center', limit_choices_to={'area_type': 'pc'})
cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center', limit_choices_to={'area_type': 'cc')

How to join tables with O2M and M2M relationship?

I have the following related data models
class Cart(models.Model):
products = models.ManyToManyField('assortment.Product', through='CartProduct')
order = models.OneToOneField('Order', on_delete=models.CASCADE, related_name='order_cart', null=True)
user = models.ForeignKey('account.Profile', on_delete=models.CASCADE, related_name='user_carts', blank=True, null=True)
class CartProduct(models.Model):
product = models.ForeignKey('assortment.Product', related_name='product_cartproducts', null=True, on_delete=models.SET_NULL)
cart = models.ForeignKey('Cart', related_name='cart_cartproducts', null=True, on_delete=models.SET_NULL)
count = models.IntegerField(blank=False, null=False, default=1)
class Order(models.Model):
pay_date = models.DateField(auto_now_add=True)
is_paid = models.BooleanField(default=False)
My code below gives an error: invalid argument "products" in prefetch_related:
Order.objects.all().select_related('order_cart').prefetch_related('products')
How can I join all three models in one request?
The query builder continues with the original table (Order), thus you have to specify the fields relative to that or relative to the previously mentioned field. Try one of the following:
'order_cart__products'
'order_cart__cart_cartproducts'
(Notice the double underscore.)

Django: Link two models with common foreign keys

Im new to django and im currently making an admin panel where i can view user orders.
I handle my orders based on the following OrderItem Model
class OrderItem(models.Model):
customer = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
product = models.ForeignKey(
Product, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
and their shipping info in the follwing ShippingAdress model
class ShippingAddress(models.Model):
customer = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
address = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
zipcode = models.CharField(max_length=200, null=True)
Views.py
orders=OrderItem.objects.select_related('customer')
context={
'orders':orders,
}
return render(request, 'index.html', context)
and in my html i want to print each customer's ShippingAdress data.
Im thinking something like the following but im stuck and it doesnt work.
{% for order in orders %}
<td>{{order.customer.address}}</td>
<td>{{order.customer.city}}</td>
{% endfor %}
What is the correct way to achieve this?
Add related_name to your ShippingAddress
class ShippingAddress(models.Model):
customer = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses")
and use it in your template like that
<td>{{order.customer.addresses.first.address}}</td>
with first you get the first address and with all all of them.

Categories