How to add data to manytomanyfield in drf - django

enter image description here
enter image description here
enter image description here
So I have a 2 models with a manytomany field. A book might be created without a publisher. When a publisher is added, I want to add it to the Books model with respect to its id any help is much appreciated

Suppose A is ManyToManyField and AA is the model, then -
First crate the instance:
Object = AA.object.create(validated_data)
then:
Object.A.add(value_to_be_added)
Now this is the guess work. Write your code for a detailed answer.
You can also use remove method to remove data from manytomanyfield.

Related

Creating a nested form field or something like that

I'm not entirely sure about the correctness of the question. In fact, I doubt whether I can express exactly what I am looking for.
Question: How can I create additional fields based on the previous selection before submitting the form?
Let's take the number of pets and the name of the pet in our example. I want how many pet names to be entered first
class UrlForm(forms.Form):
INT_CHOICES = [(x, x) for x in range(11)]
number_of_pets = forms.ChoiceField(choices=INT_CHOICES)
and then create as many Charfield fields as the selected value based on the previous selection:
#new fields as many as the number of pets
pet1 = forms.CharField()
pet2 = forms.CharField()
Of course, the variable name issue is a separate issue.
Question 2: As an alternative approach, can I create a pet name field like a tag field? As in the image:
Image taken from here. The question is appropriate but a ReactJs topic.
You can share the topic, title, term, article, anything that I need to look at. Thanks in advance.
Edit:
The pet example is purely fictional. Influenced by the image, I used this topic.

Django: Joining on fields other than IDs (Using a date field in one model to pull data from a second model)

I'm attempting to use Django to build a simple website. I have a set of blog posts that have a date field attached to indicate the day they were published. I have a table that contains a list of dates and temperatures. On each post, I would like to display the temperature on the day it was published.
The two models are as follows:
class Post(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateField()
class Temperature(models.Model):
date = models.DateField()
temperature = models.IntegerField()
I would like to be able to reference the temperature field from the second table using the date field from the first. Is this possible?
In SQL, this is a simple query. I would do the following:
Select temperature from Temperature t join Post p on t.date = p.date
I think I really have two questions:
Is it possible to brute force this, even if it's not best practice? I've googled a lot and tried using raw sql and objects.extra, but can't get them to do what I want. I'm also wary of relying on them for the long haul.
Since this seems to be a simple task, it seems likely that I'm overcomplicating it by having my models set up sub-optimally. Is there something I'm missing about how I should design my models? That is, what's the best practice for doing something like this? (I've successfully pulled the temperature into my blog post by using a foreign key in the Temperature model. But if I go that route, I don't see how I could easily make sure that my temperature dates get the correct foreign key assigned to them so that the temperature date maps to the correct post date.)
There will likely be better answers than this one, but I'll throw in my 2ยข anyway.
You could try a property inside the Post model that returns the temperature:
#property
def temperature(self):
try:
return Temperature.objects.values_list('temperature',flat=True).get(date=self.date)
except:
return None
(code not tested)
About your Models:
If you will be displaying the temperature in a Post list (a list of Posts with their temperatures), then maybe it will be simpler to code and a faster query to just add a temperature field to your Post model.
You can keep the Temperature model. Then:
Assuming you have the temperature data already present in you Temperature model at the time of Post instance creation, you can fill that new field in a custom save method.
If you get temperature data after Post creation, you cann fill in that new temperature field through a background job (maybe triggered by crontab or similar).
Sometimes database orthogonality (not repeating info in many tables) is not the best strategy. Just something to think about, depending on how often you will be querying the Post models and how simple you want to keep that query code.
I think this might be a basic approach to solve the problem
post_dates = Post.objects.all().values('date')
result_temprature = Temperature.objects.filter(date__in = post_dates).values('temperature')
Subqueries could be your friend here. Something like the following should work:
from django.db.models import OuterRef, Subquery
temps = Temperature.objects.filter(date=OuterRef('date'))
posts = Post.objects.annotate(temperature=Subquery(temps.values('temperature')[:1]))
for post in posts:
temperature = post.temperature
Then you can just iterate through posts and access the temperature off each post instance

Django store the original value of a field

I am a newbie with Django trying to create a dashboard application reporting on some key milestone dates. I want to be able to track how the key dates are changing. For example:If the kick off date has been changed 5 times I want to be able to report 1. the first date entered, 2. Current date, 3. The date before the last update.
Thank you
Your question is not clear. But for the logic you have asked one thing we can do is to make a model in which the edited dates and user will be fields. Use user as foreign key of your User model. I will just give an example model.
class Dates(models.Model):
event = models.ForeignKey(Event)
date = models.DateField()
This is a very basic method which i am saying. This is a bit complex and you will have to check if the field has changed five times and all.
For a better answer please make the question clear.

django models: Good way of storing a multiline line address as one model field

I am building some models, and I need to collect an address. Thing is, I want the address to be be collected in one model field, yet the fields for the address could span over multiple lines.
For example:
street:
city:
zip:
state:
Mine don't look like these, but you get the idea. The data needs to be stored in one model field.
TextField is a perfect choice here:
class TextField([**options])
A large text field. The default form
widget for this field is a Textarea.
Since textarea is used as a widget, it "handles" newlines for you.
I would recommend rethink the idea of storing the address inside the model field. Instead, consider having a special model(s) handling the address, since, in the future, you would probably want to query the data by city, country, street, zip etc. It would more clean, transparent and easy to filter.
See also:
how to model a postal address
django-postal
django-address
Address model snippet 1
Address model snippet 2
django.contrib.gis Address model example

Django admin: Inline of a Many2Many model with 2 foreign keys

after wracking my brain for days, I just hope someone can point me to the right approach.
I have 4 Models: Page, Element, Style and Post.
Here is my simplyfied models.py/admin.py excerpt: http://pastebin.com/uSHrG0p2
In 2 sentences:
A Element references 1 Style and 1 Post (2 FKs).
A Page can reference many Elements, Elements can be referenced by many pages (M2M).
On the admin site for Page instances I included the M2M relation as 'inline'. So that I have multiple rows to select Element-instances.
One row looking like: [My Post A with My Style X][V]
What I want is to replace that one dropdown with 2 dropdowns. One with all instances of Post and one with all instances of Style (creating Element instances in-place). So that one row would look similar to the Element admin site: [My Post A][V] [My Style X][V]
Sounds easy, but I'm just completely lost after reading and experimenting for 2 days with ModelForms, ModelAdmins, Formsets, ... .
Can I do that without custom views/forms within the Django admin functionality?
One of my approaches was to access the Post/Style instances from a PageAdminForm like this, trying to create a form widget manually from it... but failed to do so:
p = Page.objects.get(pk=1)
f = PageAdminForm(instance=p)
f.base_fields['elements'].choices.queryset[0].post
Any advice or hint which way I need to go?
Thank you for your time!
I got exactly what I wanted after removing the M2M field and linking Elements to a Page with a 3rd ForeignKey in Element:
class Element(models.Model):
page = models.ForeignKey(Page)
post = models.ForeignKey(Post)
style = models.ForeignKey(Style)
Actually a non-M2M link makes more sense for my application after all.
Memo to self: Rethink model relations before trying to outsmart Django :-(