I have 2 models.
class Unit(models.Model):
title = models.CharField(max_length=60)
def __unicode__(self):
return self.title
class UniDoc(models.Model):
title = models.CharField(max_length=100, blank=True, null=True)
units = models.ManyToManyField(Unit, blank=True)
file = models.FileField(upload_to="uploads/")
author = models.ForeignKey(User, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.file.name
How I can get unidoc list on link ti unit in template?
Django provides reverse relationships:
u = Unit.objects.get(pk=1)
u.unidoc_set.all()
So in your template, if you have passed in u from above:
{% for i in u.unidoc_set.all %}
{{ i.title }}
{% endfor %}
Related
i have 3 models (protocollo_pratica, protocollo_soggetto and protocollo_anaprat) and i need extract for each protocollo_pratica a list of soggetti with a specific "tipo" but i don't understand how to make this in django views. Thank you so much for your help.
`
this is my models.py :
`
from django.db import models
# Create your models here.
class Soggetto(models.Model):
cognome = models.CharField(max_length=100, null=True)
nome = models.CharField(max_length=100, null=True)
comune_nascita = models.CharField(max_length=100, null=True)
data_nascita = models.DateField(null=True)
codice_fiscale = models.CharField(max_length=16, null=True)
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
return self.nome
class Pratica(models.Model):
oggetto = models.CharField(max_length=100)
anagrafe = models.ManyToManyField(Soggetto,
through='Anaprat',
through_fields=('pratica', 'soggetto'),)
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
return self.oggetto
class Anaprat(models.Model):
tipo=models.CharField( max_length=50)
pratica=models.ForeignKey("Pratica", related_name='pratiche', on_delete=models.CASCADE)
soggetto=models.ForeignKey("Soggetto", related_name='soggetti', on_delete=models.CASCADE)
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
return f"{self.tipo, self.soggetto}"`
and this is my sql query :
`SELECT
p.id,
pa.tipo tipo,
ps.cognome,
ps.nome,
ps.data_nascita,
ps.comune_nascita
from
(SELECT
id id
from protocollo_pratica pp ) p,
protocollo_anaprat pa
left JOIN protocollo_soggetto ps
on ps.id=pa.soggetto_id
where p.id=pa.pratica_id`
SerializerClass:
class VacancySerializer(serializers.ModelSerializer):
organization_small_name = serializers.CharField(source='organization.short_name', read_only=True)
class Meta:
model = Vacancy
fields = ['organization', 'description', 'specs', 'type', 'publication_date',
'is_published', 'withdrawal_data', 'organization_small_name', ]
read_only_fields = ['publication_date', 'is_published', 'withdrawal_data',]
ViewSet:
class VacancyViewSet(viewsets.ModelViewSet):
queryset = Vacancy.objects.all()
serializer_class = VacancySerializer
filter_backends = [filters.SearchFilter]
search_fields = ['organization_small_name']
...
Model:
class Vacancy(models.Model):
organization = models.OneToOneField(DictOrganization, on_delete=models.CASCADE, related_name='vacancies')
description = models.TextField('Описание')
specs = models.ManyToManyField(DictSpec, blank=True)
type = models.CharField('Тип', max_length=20, choices=VacancyType.choices(), default=VacancyType.PRACTICE.value)
publication_date = models.DateField('Дата публикации', null=True, blank=True)
is_published = models.BooleanField('Опубликовано', default=False)
withdrawal_data = models.DateField('Дата снятия с публикации', null=True, blank=True)
My goal is to make API search by 'organization_small_name' field
that is in VacancySerializer.
Server runs successfully, but as soon as i add ?search parameter, i get next error:
Why it doesn't recognize 'organization_small_name' field, even thought it is decribed in serializer, and how can i fix it?
Creating Django REST FRamework API. Using Abstract User and email is the default logging parameter using.
AttributeError at /post/
Got AttributeError when attempting to get a value for field email on serializer UserSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Post instance.
Original exception text was: 'Post' object has no attribute 'email'.
class PostSerializer(ModelSerializer):
category = ReadOnlyField(source='category.name')
author = UserSerializer(source='user.email')
#question = serializers.CharField(source='question.text', read_only=True)
class Meta:
model = Post
fields = '__all__'
class User(AbstractUser):
username = models.CharField("Username", max_length=50, unique=True)
email = models.EmailField("Email Address", max_length=254, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE, to_field='email')
category = models.ForeignKey(Category, related_name='categorys', on_delete=models.CASCADE)
body = models.TextField()
image = models.ImageField(upload_to='blog/%Y/%m/%d', blank=True)
publish = models.DateTimeField(default=timezone.now)
rating = models.IntegerField("Rumor Rate", validators=[MaxValueValidator(5), MinValueValidator(0)], default=1, null=True)
created = models.DateTime[![enter image description here][1]][1]Field(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
I suppose you want to return the author's email in the author field when you request the Post endpoint. You may also convert the author field in the serializer to a ReadOnlyField (as category) and specify source='author.email', since your model foreign key is named like that:
class PostSerializer(ModelSerializer):
category = ReadOnlyField(source='category.name')
author = ReadOnlyField(source='author.email')
# ...
I have an object (a blogpost) which can have multiple tags in django. I'm trying to get related objects with one or more of these same tags.
For example: You have a blogpost with a few tags, like 'food', 'drinks' and 'restaurants'. When you open this blogpost, there are displayed some 'related' blogposts (meaning they share one or more tags). An example of such a related blogpost would have the tags: 'soda', 'lemonade' and 'drinks'.
Here is my view:
instance = get_object_or_404(Blog, id=id)
tags = instance.tags.values()
related = []
for x in tags: #to put all the tags in an array
related.append(x['name'])
for a in Blog.objects.raw('SELECT * FROM "blog_table" WHERE related in "blog_table"."tags"'):
print (a.name) #this should display the name of all the related blogposts (probably including itself)
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=500)
number = models.IntegerField(null=True, blank=True)
def __str__(self):
return str(self.number) + ' ' + self.name
class Blog(models.Model):
name = models.CharField(null=False, max_length=500, verbose_name='title of blogpost', unique=True)
body = models.TextField(null=False, verbose_name='body of the blogpost')
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __str__(self):
return self.name
To get the blogs that have similar instance tag, you can do this:
tags = instance.tag.all()
for tag in tags:
print(Blog.objects.filter(tags=tag))
Using Flask SQLAlchemy, I'm trying to use a Many-to-Many relationship using a helper table with additional fields.
Model definition:
prodord = db.Table('prodord',
db.Column('prod_id', db.Integer, db.ForeignKey('Product.id'), primary_key=True),
db.Column('order_id', db.Integer, db.ForeignKey('AOrder.id'), primary_key=True),
db.Column('quantity', db.Integer)
)
class Product(db.Model):
__tablename__ = 'Product'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class User(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class AOrder(db.Model):
__tablename__ = 'AOrder'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'))
timedate = db.Column(db.String)
products = db.relationship('Product', secondary=prodord, lazy='subquery',
backref=db.backref('orders', lazy=True))
Invoking the template:
#app.route('/orders')
def page_orders():
all_orders = AOrder.query.all()
return render_template('orders.html', orders=all_orders)
How do I use the quantity value on the template? product.quantity is empty but p.name has value:
{% for o in orders %}
<tr>
<td>{{o.timedate}}</td>
<td>
{% for p in o.products %}
{{p.quantity}} {{p.name}} <br />
{% endfor %}
</td>
</tr>
{% endfor %}
You've set up your relationship using an association table, which essentially becomes a transparent link between the Product and Order models.
Since you want to store extra data in that link table, you need to upgrade it to be an association object, just like your other models.
The documentation goes into the detail of how to do that, here's an example from there:
class Association(Base):
__tablename__ = 'association'
left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
extra_data = Column(String(50))
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Association", back_populates="parent")
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
parents = relationship("Association", back_populates="child")