Let's say I have a model called Schools.
And also I have a Schools instance that I don't want to store in my database.
temp_school = Schools(school_id='temp_1')
Also I have all schools
schools = Schools.objects.all()
Now, how can I add my temp_school to the schools, so that I can use it as my new queryset in my view?
Related
what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
customer = request.user.customer
The request object has a user, the user is the authenticated user (if no user is authenticated then the AnonymousUser object is returned instead). In this example the User model (i.e. the user table) has a field called customer and we are accessing that field.
product = Product.objects.get(id=productId)
Here we are simply querying the Product table for a specific product with the given productId. Note, Django will raise an error if two records are returned when you use the .get() method (i.e. if two rows in the Product table have the same productId.
order, created = Order.objects.get_or_create(customer=customer, complete=False)
Next we use the get_or_create() method to look up an order based off of the customer (the value of which we extracted above. If an order cannot be found we will create one instead. The value of createdwill be True if a neworder` was created or False if one already existed.
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
Just as above we are getting or creating an OrderItem using the order and product fields.
Consider the following code:
views.py
class BHA_UpdateView(UpdateView):
model = BHA_overall
pk_url_kwarg = 'pk_alt'
form_class = BHA_overall_Form
To my understanding, pk_url_kwarg = 'pk_alt' will query and return instances of model = BHA_overall.
Is there any way that I can force pk_url_kwarg to query
& return other model instances defined in models.py (like model = other_model), while having my get_object() method to return objects in model = BHA_overall? What CBV should I use (I think UpdateView is not a good choice in this case)?
++ I'm trying to make a page that allows users to manage information about the product they use. So, ultimately I will implement forms, and the user input needs to be saved in DB
++ I need pk_url_kwarg = 'pk_alt' to query other models and generate url. But I still need get_object() method to return objects in model = BHA_overall to generate form fields on the user side.
From my understanding you need a django form generated from BHA_overall, but the data should be saved to AnotherModel right?
I will propose 2 solutions to this problem, Choose what best fits you.
Multiple views:
Have multiple views for the task, What I mean is create a view which creates the form for the frontend using BHA_overall, you can create both Create and Update view this way and update view's initial could be overwritten so form will have expected value when editing. And now post the data to another view which handles the post data. This view can have your AnotherModel doing its thing.
Using Django Form:
If you dont like having multiple views, You can keep things simple by creating a form yourself. Create a DjangoForm with the same fields you want to show to the user and use it in to create your own views, Now you wont need BHA_overall and use your AnotherModel to save datal.
I have been countering a problem of retrieving a 'sub' objects from an objects list:
class BusinessLike(models.Model):
user = models.ForeignKey(AppUser, related_name='user_business_likes')
business = models.ForeignKey(Business, related_name='business_likes')
class Meta:
unique_together = (('user', 'business'),)
How do I get 'Business' object for each 'BusinessLike' object in app_user.user_businesses_likes (without looping over the list and making new list with business_like.business)?
You can use values or values_list:
businesses = BusinessLike.objects.values('business')
businesses = BusinessLike.objects.values_list('business', flat=True)
However, this won't give you a list of objects, you only get a list of foreign key ids.
Django doc about values and value_list.
If you want to avoid having additional lookups every time you do business_like.business, you could use select_related:
business_likes = BusinessLike.objects.select_related('business')
In this case, when you loop on each BusinessLike object and do business_like.business, django won't join the database anymore but it's cached in memory already.
Django doc about select_related.
If you are doing this in the view, you might find it easier to make a new queryset starting with the Business model.
businesses = Business.objects.filter(business_likes__user=app_user)
I'm not sure that you need to create the BusinessLike model like this. You could add a many to many field to the AppUser model (or the Business model if you prefer).
class AppUser(models.Model):
business_likes = models.ManyToManyField(Business)
Django will take care of creating the intermediate table, and then you can do queries like:
businesses = app_user.business_likes.all()
I need to make a queryset on django and I want to filter both a model and its related model. Like I need to get all PartRequest's that are created by a seller and I want to retrieve only his bid attatched.
class PartRequest(models.Model):
class Bid(models.Model):
seller = models.ForeignKey(UserSeller, related_name='seller_bid')
request = models.ForeignKey(PartRequest, related_name='request_bid')
If I understand correctly this is what you want
bids = Bid.objects.filter(seller=your seller here)
partRequests = bids.values_list('request', flat=True)
You can't get it as an instance of a particular model if you want it as a single object. Take a look at raw() for what you want.
https://docs.djangoproject.com/en/dev/topics/db/sql/
I am trying to write my first unit test in Django. It's for a Staff registration form.
The Staff model for the form has a OneToOne relation with a UserProfile (AUTH_PROFILE_MODULE).
The UserProfile has a OneToOne relation with django.contrib.auth.models.User.
I am using https://github.com/dnerdy/factory_boy to create a test model instance for the staff model. The idea is to use a StaffFactory so I can easily create test model instances. To create a bound form I need to pass it a data dict. I thought it would be convenient to just use django.forms.models.model_to_dict to convert my model instance into a data dict when testing the form.
Now, my problem is: model_to_dict does not traverse the foreign keys of my Staff model (Staff->UserProfile->User). This means the form stays invalid since required fields like the User's email are still missing inside the form data.
Currently my StaffRegistrationFormTest looks like:
class StaffRegistrationFormTest(unittest.TestCase):
def test_success(self):
staff1 = StaffFactory()
form = StaffRegistrationForm(model_to_dict(staff1))
# print jsonpickle.encode(model_to_dict(staff1))
self.assertTrue(form.is_valid(), form.errors)
Is there a way to pass in a dict, where the foreign keys are serialized by re-using a model instance?
So it seems as if one way of solving this is by creating additional dictionaries for the OneToOne fields of the Staff model and merging them.
This makes the test pass:
data = dict(model_to_dict(staff1).items() +
model_to_dict(staff1.profile).items() +
model_to_dict(staff1.profile.user).items())
form = StaffRegistrationForm(data=data)
self.assertTrue(form.is_valid(), form.errors)
I am not sure if this is the way to go in terms of best practice. Feel free to comment if this it completely against the grain.