Related
Ok, this is a hard one to explain.
I Have these models:
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Product(models.Model):
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(null=True, max_length=99, unique=True, blank=True)
image = DefaultStaticImageField(null=True, blank=True,default='images/item_gC0XXrx.png')
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True)
class Order(models.Model):
item = models.ForeignKey(Product, on_delete=models.CASCADE, default='')
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
item_qty = models.IntegerField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
My ultimate goal is to be able to create an 'Order' pulling items from a specific supplier.
Now, I have no idea as to make that happen - how do I create an instance of an 'Order',in a form of some sort, that will fetch items from the selected supplier and not all items from everybody else?
You are looking for limit_choices_to
I tried to insert data into the table Account, but I keep getting this error message.
I delete all my migrations and make migrations again but I keep getting this error.
Here is my models.
class Student(models.Model):
user = models.OneToOneField(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
section = models.ForeignKey(Section, on_delete=models.CASCADE, default=1)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
batch = models.CharField(max_length=15, null=True, blank=True)
USN = models.CharField(primary_key='True', max_length=100)
DOB = models.DateField(default='1998-01-01')
profile_image = models.ImageField(upload_to='student/profile_images/%Y/%m/%d/', blank=True, null=True)
address = models.CharField(max_length=300, null=True, blank=True)
nationality = models.CharField(max_length=100, null=True, blank=True)
guardian_name = models.CharField(max_length=200, null=True, blank=True)
guardian_number = models.CharField(max_length=15, null=True, blank=True)
guardian_address = models.CharField(max_length=300, null=True, blank=True)
blood_group = models.CharField(max_length=3, null=True, blank=True)
exam_name = models.CharField(max_length=300, null=True, blank=True)
background = models.CharField(max_length=300, null=True, blank=True)
passing_year = models.CharField(max_length=8, null=True, blank=True)
score = models.CharField(max_length=10, null=True, blank=True)
school_name = models.CharField(max_length=300, null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
certificate = models.FileField(upload_to='certificates/%Y/%m/%d/', null=True, blank=True)
Here is Account model.
class Account(AbstractBaseUser, PermissionsMixin):
unid = models.CharField(max_length=20, unique=True, null=True, blank=True)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)
user_permissions = models.ManyToManyField(
Permission,
verbose_name=_('user permissions'),
blank=True,
null=True,
help_text=_('Specific permissions for this user.'),
related_name="user_set",
related_query_name="user",
)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
registered = models.BooleanField(default=False)
so what I did is that when I create account if the is_student is True I create a signals that going to create student model for that account instance automatically.
here is the signals
def create_student_or_teacher(sender, created, instance, **kwargs):
if created:
if instance.is_student:
Student.objects.create(
user=instance,
USN=instance.unid,
)
elif instance.is_teacher:
Teacher.objects.create(
user=instance,
id=instance.unid,
)
So when I create the account for student the tracker will highlight in the signals Student.objects.create(...)
If you have any idea I hope it would help me.
UPDATED:
When I'm creating teacher it is working find.
here is the teacher model
class Teacher(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
salary = models.IntegerField(default=1)
school = models.ForeignKey(School, blank=True, null=True, on_delete=models.CASCADE)
section = models.ForeignKey(Section, blank=True, null=True, on_delete=models.CASCADE)
user = models.OneToOneField(Account, on_delete=models.CASCADE, null=True)
id = models.CharField(primary_key=True, max_length=100)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
DOB = models.DateField(default='1980-01-01')
profile_image = models.ImageField(upload_to='teacher/profile_images/%Y/%m/%d/', blank=True, null=True)
nationality = models.CharField(max_length=300, null=True, blank=True)
address = models.CharField(max_length=300, null=True, blank=True)
Finally after few hours I solved my error it was simple
in the section I set default value which was not exist
so I just change the value to an exist one and that was it.
I have a two models, Person and Video.
Below viewset allows me all methods like POST, PATCH, DELETE, GET.
class PersonViewSet(viewsets.ModelViewSet):
queryset = apis_models.Person.objects.all()
serializer_class = apis_serializers.PersonSerializer
permission_classes = [HasPermPage]
Video model is associated with person model through Target model which is my main problem. Each person has few videos.
Now what I need is when I do "/person/{id}/" I should get person details along with all videos details it associated with.
Please let me know what change needs to be done to above ViewSet.
Models and Serializer:
class Video(DFModel):
source = models.ForeignKey(Source, models.DO_NOTHING)
creator = models.ForeignKey(
Creator, models.DO_NOTHING, blank=True, null=True)
title = models.CharField(max_length=500)
views = models.IntegerField(blank=True, null=True)
likes = models.IntegerField(blank=True, null=True)
dislikes = models.IntegerField(blank=True, null=True)
tags = models.TextField(blank=True, null=True)
upload_date = models.DateTimeField(blank=True, null=True)
page_url = models.TextField(blank=True, null=True)
video_url = models.TextField(blank=True, null=True)
thumb_url = models.TextField(blank=True, null=True)
sfw = models.BooleanField(blank=True, null=True)
category = models.CharField(max_length=20, blank=True, null=True)
reviewed = models.TextField(blank=True, null=True)
severity = models.CharField(max_length=10, blank=True, null=True)
origin = models.CharField(max_length=20, blank=True, null=True)
organization_id = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Target(DFModel):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
video = models.ForeignKey(
'Video', models.DO_NOTHING, blank=True, null=True)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Meta:
db_table = 'target'
class PersonSerializer(CustomSerializer):
class Meta:
model = apis_models.Person
fields = '__all__'
class TargetSerializer(CustomSerializer):
class Meta:
model = apis_models.Target
fields = '__all__'
extra_fields = ['monthly_growth', 'vulnerablility_score']
class VideoSerializer(CustomSerializer):
source = SourceSerializer(read_only=True)
creator = CreatorSerializer(read_only=True)
class Meta:
model = apis_models.Video
fields = '__all__'
It looks like you have a ManyToMany relation between Person and Video, so, I suggest you to change your models to be like:
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
videos = models.ManyToManyField(Video, through='Target', related_name="people") # Field that will have the videos of a Person
Once you have that, I suggest you to change your PersonSerializer object to be:
class PersonSerializer(CustomSerializer):
videos = VideoSerializer(source='videos', many=True)
class Meta:
model = apis_models.Person
fields = '__all__'
If you can't change your models to support ManyToMany fields I suggest you to do the following:
class Person(models.Model):
name = models.CharField(unique=True, max_length=45)
nationality = models.CharField(max_length=50, blank=True, null=True)
profession = models.CharField(max_length=50, blank=True, null=True)
avatar = models.CharField(max_length=100, blank=True, null=True)
active_scraping = models.BooleanField(blank=True, null=True)
vuln_score = models.FloatField(blank=True, null=True, default=None)
reviewed = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def videos(self):
return Video.objects.filter(
id__in=Target.objects.filter(person=self).values('video')
)
And use the same serializer I used in the first part of the answer.
I have a query that links five tables. In some of them I need one (name from contractor) field. Therefore, I want to optimize this and select only one field), and not the entire table. How can I edit this code?
paymentsss = Transaction.objects.all().select_related('currency',
'payment_source__payment_type', 'deal__service','deal__service__contractor')
Turns into
SELECT "processing"."transaction"."id",
"processing"."transaction"."currency_id",
"processing"."transaction"."deal_id",
"processing"."transaction"."service_instance_id",
"processing"."transaction"."payment_source_id",
"processing"."transaction"."payment_date",
"processing"."transaction"."amount",
"processing"."transaction"."status",
"processing"."transaction"."context",
"processing"."currency"."id",
"processing"."currency"."name",
"processing"."currency"."iso_name",
"processing"."currency"."minor_unit",
"processing"."deal"."id",
"processing"."deal"."service_id",
"processing"."deal"."currency_id",
"processing"."deal"."adapter_account_id",
"processing"."deal"."amounts_rule",
"processing"."deal"."comission_rule",
"processing"."deal"."weight_rule",
"processing"."deal"."active",
"processing"."deal"."provider_enabled",
"processing"."deal"."min_amount",
"processing"."deal"."max_amount",
"processing"."deal"."payment_types",
"processing"."deal"."params",
"processing"."deal"."contractor_params",
"processing"."deal"."tags",
"processing"."service"."id",
"processing"."service"."flow_id",
"processing"."service"."currency_id",
"processing"."service"."contractor_id",
"processing"."service"."amount",
"processing"."service"."callback_url",
"processing"."service"."definition",
"processing"."service"."name",
"processing"."service"."description",
"processing"."service"."charge_strategy",
"processing"."service"."routine",
"processing"."service"."tags",
"processing"."contractor"."id",
"processing"."contractor"."name",
"processing"."contractor"."inn",
"processing"."contractor"."kpp",
"processing"."contractor"."bank_reg_id",
"processing"."contractor"."bank_reg_date",
"processing"."contractor"."slug",
"processing"."contractor"."uuid",
"processing"."contractor"."is_nds_payer",
"processing"."contractor"."tag",
"processing"."payer_payment_source"."id",
"processing"."payer_payment_source"."payer_id",
"processing"."payer_payment_source"."payment_type_id",
"processing"."payer_payment_source"."source_details",
"processing"."payment_type"."id",
"processing"."payment_type"."name",
"processing"."payment_type"."group_name"
FROM "processing"."transaction"
LEFT OUTER JOIN "processing"."currency"
ON ("processing"."transaction"."currency_id" = "processing"."currency"."id")
LEFT OUTER JOIN "processing"."deal"
ON ("processing"."transaction"."deal_id" = "processing"."deal"."id")
LEFT OUTER JOIN "processing"."service"
ON ("processing"."deal"."service_id" = "processing"."service"."id")
LEFT OUTER JOIN "processing"."contractor"
ON ("processing"."service"."contractor_id" = "processing"."contractor"."id")
LEFT OUTER JOIN "processing"."payer_payment_source"
ON ("processing"."transaction"."payment_source_id" = "processing"."payer_payment_source"."id")
LEFT OUTER JOIN "processing"."payment_type"
ON ("processing"."payer_payment_source"."payment_type_id" = "processing"."payment_type"."id")
ORDER BY "processing"."transaction"."id" DESC
What i want to delete
I highlighted in red those columns that I wanted to delete.
Some of models from models.py
class Contractors(models.Model):
id = models.IntegerField(blank=True, null=False, primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
inn = models.CharField(max_length=14, blank=True, null=True)
kpp = models.CharField(max_length=14, blank=True, null=True)
bank_reg_id = models.CharField(max_length=255, blank=True, null=True)
bank_reg_date = models.DateField(blank=True, null=True)
slug = models.CharField(max_length=255, blank=True, null=True)
uuid = models.CharField(max_length=36, blank=True, null=True)
is_nds_payer = models.BooleanField(blank=True, null=True)
tag = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = '"processing"."contractor"'
class PaymentType(models.Model):
id = models.CharField(max_length=75, blank=True, null=False, primary_key=True)
name = models.CharField(max_length=128, blank=True, null=True)
group_name = models.CharField(max_length=64, blank=True, null=True)
class Meta:
managed = False
db_table = '"processing"."payment_type"'
class Service(models.Model):
id = models.IntegerField(db_index=True, blank=True, null=False, primary_key=True)
flow_id = models.IntegerField(blank=True, null=True)
currency_id = models.SmallIntegerField(blank=True, null=True)
contractor = models.ForeignKey(Contractors, blank=True, null=True, on_delete=models.CASCADE)
amount = models.IntegerField(blank=True, null=True)
callback_url = models.CharField(max_length=128, blank=True, null=True)
definition = models.TextField(blank=True, null=True) # This field type is a guess.
name = models.CharField(max_length=255, blank=True, null=True)
description = models.TextField(blank=True, null=True)
charge_strategy = models.CharField(max_length=64, blank=True, null=True)
routine = models.TextField(blank=True, null=True) # This field type is a guess.
tags = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = '"processing"."service"'
class Transaction(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE)
deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE)
service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE)
payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE)
payment_date = models.DateTimeField(blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
context = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = '"processing"."transaction"'
You can use defer to not load up the fields from related models:
https://docs.djangoproject.com/en/2.2/ref/models/querysets/#defer
So a (not complete) modification of your query to remove currency name:
paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service','deal__service__contractor').defer('currency__name')
I decided this by simply deleting the fields I did not need from the model.
I trying extend existed models so I added 'thumbnails' in to it. Unfortunately function related to this is not recognized and django console gives me:
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
NameError: name '_get_upload_image' is not defined
Could someone help me with this issue?
Django 1.6.5 models.py (short version)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
class Meta:
unique_together = (
("url", "user"),
)
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
I solved this through placing function on top of class
class Feed(models.Model):
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)